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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1105  ! raeburn     4: # $Id: lonnet.pm,v 1.1104 2011/02/24 23:55:58 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1090    raeburn    98: use File::Copy;
1.676     albertel   99: 
1.195     www       100: my $readit;
1.550     foxr      101: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.993     raeburn   199: sub get_server_loncaparev {
1.1073    raeburn   200:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             undef($lonhost);
                    204:         }
                    205:     }
                    206:     if (!defined($lonhost)) {
                    207:         if (defined(&domain($dom,'primary'))) {
                    208:             $lonhost=&domain($dom,'primary');
                    209:             if ($lonhost eq 'no_host') {
                    210:                 undef($lonhost);
                    211:             }
                    212:         }
                    213:     }
                    214:     if (defined($lonhost)) {
1.1073    raeburn   215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $loncaparev;
                    220:             }
                    221:         }
                    222:         my ($answer,$loncaparev);
                    223:         my @ids=&current_machine_ids();
                    224:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    225:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   226:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   227:                 $loncaparev = $1;
                    228:             }
                    229:         } else {
                    230:             $answer = &reply('serverloncaparev',$lonhost);
                    231:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    232:                 if ($caller eq 'loncron') {
                    233:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   234:                     $ua->timeout(4);
1.1073    raeburn   235:                     my $protocol = $protocol{$lonhost};
                    236:                     $protocol = 'http' if ($protocol ne 'https');
                    237:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    238:                     my $request=new HTTP::Request('GET',$url);
                    239:                     my $response=$ua->request($request);
                    240:                     unless ($response->is_error()) {
                    241:                         my $content = $response->content;
1.1081    raeburn   242:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   243:                             $loncaparev = $1;
                    244:                         }
                    245:                     }
                    246:                 } else {
                    247:                     $loncaparev = $loncaparevs{$lonhost};
                    248:                 }
1.1081    raeburn   249:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   250:                 $loncaparev = $1;
                    251:             }
1.993     raeburn   252:         }
1.1073    raeburn   253:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   254:     }
                    255: }
                    256: 
1.1074    raeburn   257: sub get_server_homeID {
                    258:     my ($hostname,$ignore_cache,$caller) = @_;
                    259:     unless ($ignore_cache) {
                    260:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    261:         if (defined($cached)) {
                    262:             return $serverhomeID;
                    263:         }
                    264:     }
                    265:     my $cachetime = 12*3600;
                    266:     my $serverhomeID;
                    267:     if ($caller eq 'loncron') { 
                    268:         my @machine_ids = &machine_ids($hostname);
                    269:         foreach my $id (@machine_ids) {
                    270:             my $response = &reply('serverhomeID',$id);
                    271:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    272:                 $serverhomeID = $response;
                    273:                 last;
                    274:             }
                    275:         }
                    276:         if ($serverhomeID eq '') {
                    277:             $serverhomeID = $machine_ids[-1];
                    278:         }
                    279:     } else {
                    280:         $serverhomeID = $serverhomeIDs{$hostname};
                    281:     }
                    282:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    283: }
                    284: 
1.1       albertel  285: # -------------------------------------------------- Non-critical communication
                    286: sub subreply {
                    287:     my ($cmd,$server)=@_;
1.838     albertel  288:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      289:     #
                    290:     #  With loncnew process trimming, there's a timing hole between lonc server
                    291:     #  process exit and the master server picking up the listen on the AF_UNIX
                    292:     #  socket.  In that time interval, a lock file will exist:
                    293: 
                    294:     my $lockfile=$peerfile.".lock";
                    295:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    296: 	sleep(1);
                    297:     }
                    298:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      299:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      300:     #
1.550     foxr      301:     #   We'll give the connection a few tries before abandoning it.  If
                    302:     #   connection is not possible, we'll con_lost back to the client.
                    303:     #   
                    304:     my $client;
                    305:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    306: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    307: 				      Type    => SOCK_STREAM,
                    308: 				      Timeout => 10);
1.869     albertel  309: 	if ($client) {
1.550     foxr      310: 	    last;		# Connected!
1.850     albertel  311: 	} else {
1.853     albertel  312: 	    &create_connection(&hostname($server),$server);
1.550     foxr      313: 	}
1.850     albertel  314:         sleep(1);		# Try again later if failed connection.
1.550     foxr      315:     }
                    316:     my $answer;
                    317:     if ($client) {
1.704     albertel  318: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      319: 	$answer=<$client>;
                    320: 	if (!$answer) { $answer="con_lost"; }
                    321: 	chomp($answer);
                    322:     } else {
                    323: 	$answer = 'con_lost';	# Failed connection.
                    324:     }
1.1       albertel  325:     return $answer;
                    326: }
                    327: 
                    328: sub reply {
                    329:     my ($cmd,$server)=@_;
1.838     albertel  330:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  331:     my $answer=subreply($cmd,$server);
1.65      www       332:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  333:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       334:                 " $cmd to $server returned $answer</font>");
                    335:     }
1.1       albertel  336:     return $answer;
                    337: }
                    338: 
                    339: # ----------------------------------------------------------- Send USR1 to lonc
                    340: 
                    341: sub reconlonc {
1.891     albertel  342:     my ($lonid) = @_;
                    343:     my $hostname = &hostname($lonid);
                    344:     if ($lonid) {
                    345: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    346: 	if ($hostname && -e $peerfile) {
                    347: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    348: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    349: 					     Type    => SOCK_STREAM,
                    350: 					     Timeout => 10);
                    351: 	    if ($client) {
                    352: 		print $client ("reset_retries\n");
                    353: 		my $answer=<$client>;
                    354: 		#reset just this one.
                    355: 	    }
                    356: 	}
                    357: 	return;
                    358:     }
                    359: 
1.836     www       360:     &logthis("Trying to reconnect lonc");
1.1       albertel  361:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  362:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  363: 	my $loncpid=<$fh>;
                    364:         chomp($loncpid);
                    365:         if (kill 0 => $loncpid) {
                    366: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    367:             kill USR1 => $loncpid;
                    368:             sleep 1;
1.836     www       369:          } else {
1.12      www       370: 	    &logthis(
1.672     albertel  371:                "<font color=\"blue\">WARNING:".
1.12      www       372:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  373:         }
                    374:     } else {
1.836     www       375: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  376:     }
                    377: }
                    378: 
                    379: # ------------------------------------------------------ Critical communication
1.12      www       380: 
1.1       albertel  381: sub critical {
                    382:     my ($cmd,$server)=@_;
1.838     albertel  383:     unless (&hostname($server)) {
1.672     albertel  384:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       385:                " Critical message to unknown server ($server)</font>");
                    386:         return 'no_such_host';
                    387:     }
1.1       albertel  388:     my $answer=reply($cmd,$server);
                    389:     if ($answer eq 'con_lost') {
                    390: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  391: 	my $answer=reply($cmd,$server);
1.1       albertel  392:         if ($answer eq 'con_lost') {
                    393:             my $now=time;
                    394:             my $middlename=$cmd;
1.5       www       395:             $middlename=substr($middlename,0,16);
1.1       albertel  396:             $middlename=~s/\W//g;
                    397:             my $dfilename=
1.305     www       398:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    399:             $dumpcount++;
1.1       albertel  400:             {
1.448     albertel  401: 		my $dfh;
                    402: 		if (open($dfh,">$dfilename")) {
                    403: 		    print $dfh "$cmd\n"; 
                    404: 		    close($dfh);
                    405: 		}
1.1       albertel  406:             }
                    407:             sleep 2;
                    408:             my $wcmd='';
                    409:             {
1.448     albertel  410: 		my $dfh;
                    411: 		if (open($dfh,"<$dfilename")) {
                    412: 		    $wcmd=<$dfh>; 
                    413: 		    close($dfh);
                    414: 		}
1.1       albertel  415:             }
                    416:             chomp($wcmd);
1.7       www       417:             if ($wcmd eq $cmd) {
1.672     albertel  418: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       419:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  420:                 &logperm("D:$server:$cmd");
                    421: 	        return 'con_delayed';
                    422:             } else {
1.672     albertel  423:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       424:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  425:                 &logperm("F:$server:$cmd");
                    426:                 return 'con_failed';
                    427:             }
                    428:         }
                    429:     }
                    430:     return $answer;
1.405     albertel  431: }
                    432: 
1.755     albertel  433: # ------------------------------------------- check if return value is an error
                    434: 
                    435: sub error {
                    436:     my ($result) = @_;
1.756     albertel  437:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  438: 	if ($2 == 2) { return undef; }
                    439: 	return $1;
                    440:     }
                    441:     return undef;
                    442: }
                    443: 
1.783     albertel  444: sub convert_and_load_session_env {
                    445:     my ($lonidsdir,$handle)=@_;
                    446:     my @profile;
                    447:     {
1.917     albertel  448: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    449: 	if (!$opened) {
1.915     albertel  450: 	    return 0;
                    451: 	}
1.783     albertel  452: 	flock($idf,LOCK_SH);
                    453: 	@profile=<$idf>;
                    454: 	close($idf);
                    455:     }
                    456:     my %temp_env;
                    457:     foreach my $line (@profile) {
1.786     albertel  458: 	if ($line !~ m/=/) {
                    459: 	    return 0;
                    460: 	}
1.783     albertel  461: 	chomp($line);
                    462: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    463: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    464:     }
                    465:     unlink("$lonidsdir/$handle.id");
                    466:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    467: 	    0640)) {
                    468: 	%disk_env = %temp_env;
                    469: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    470: 	untie(%disk_env);
                    471:     }
1.786     albertel  472:     return 1;
1.783     albertel  473: }
                    474: 
1.374     www       475: # ------------------------------------------- Transfer profile into environment
1.780     albertel  476: my $env_loaded;
                    477: sub transfer_profile_to_env {
1.788     albertel  478:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    479:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       480: 
1.720     albertel  481:     if (!defined($lonidsdir)) {
                    482: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    483:     }
                    484:     if (!defined($handle)) {
                    485:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    486:     }
                    487: 
1.786     albertel  488:     my $convert;
                    489:     {
1.917     albertel  490:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    491: 	if (!$opened) {
1.915     albertel  492: 	    return;
                    493: 	}
1.786     albertel  494: 	flock($idf,LOCK_SH);
                    495: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    496: 		&GDBM_READER(),0640)) {
                    497: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    498: 	    untie(%disk_env);
                    499: 	} else {
                    500: 	    $convert = 1;
                    501: 	}
                    502:     }
                    503:     if ($convert) {
                    504: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    505: 	    &logthis("Failed to load session, or convert session.");
                    506: 	}
1.374     www       507:     }
1.783     albertel  508: 
1.786     albertel  509:     my %remove;
1.783     albertel  510:     while ( my $envname = each(%env) ) {
1.433     matthew   511:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    512:             if ($time < time-300) {
1.783     albertel  513:                 $remove{$key}++;
1.433     matthew   514:             }
                    515:         }
                    516:     }
1.783     albertel  517: 
1.619     albertel  518:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  519:     $env_loaded=1;
1.783     albertel  520:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   521:         &delenv($expired_key);
1.374     www       522:     }
1.1       albertel  523: }
                    524: 
1.916     albertel  525: # ---------------------------------------------------- Check for valid session 
                    526: sub check_for_valid_session {
                    527:     my ($r) = @_;
                    528:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    529:     my $lonid=$cookies{'lonID'};
                    530:     return undef if (!$lonid);
                    531: 
                    532:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    533:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    534:     return undef if (!-e "$lonidsdir/$handle.id");
                    535: 
1.917     albertel  536:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    537:     return undef if (!$opened);
1.916     albertel  538: 
                    539:     flock($idf,LOCK_SH);
                    540:     my %disk_env;
                    541:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    542: 	    &GDBM_READER(),0640)) {
                    543: 	return undef;	
                    544:     }
                    545: 
                    546:     if (!defined($disk_env{'user.name'})
                    547: 	|| !defined($disk_env{'user.domain'})) {
                    548: 	return undef;
                    549:     }
                    550:     return $handle;
                    551: }
                    552: 
1.830     albertel  553: sub timed_flock {
                    554:     my ($file,$lock_type) = @_;
                    555:     my $failed=0;
                    556:     eval {
                    557: 	local $SIG{__DIE__}='DEFAULT';
                    558: 	local $SIG{ALRM}=sub {
                    559: 	    $failed=1;
                    560: 	    die("failed lock");
                    561: 	};
                    562: 	alarm(13);
                    563: 	flock($file,$lock_type);
                    564: 	alarm(0);
                    565:     };
                    566:     if ($failed) {
                    567: 	return undef;
                    568:     } else {
                    569: 	return 1;
                    570:     }
                    571: }
                    572: 
1.5       www       573: # ---------------------------------------------------------- Append Environment
                    574: 
                    575: sub appenv {
1.949     raeburn   576:     my ($newenv,$roles) = @_;
                    577:     if (ref($newenv) eq 'HASH') {
                    578:         foreach my $key (keys(%{$newenv})) {
                    579:             my $refused = 0;
                    580: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    581:                 $refused = 1;
                    582:                 if (ref($roles) eq 'ARRAY') {
                    583:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    584:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    585:                         $refused = 0;
                    586:                     }
                    587:                 }
                    588:             }
                    589:             if ($refused) {
                    590:                 &logthis("<font color=\"blue\">WARNING: ".
                    591:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    592:                          .'</font>');
                    593: 	        delete($newenv->{$key});
                    594:             } else {
                    595:                 $env{$key}=$newenv->{$key};
                    596:             }
                    597:         }
                    598:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    599:         if ($opened
                    600: 	    && &timed_flock($env_file,LOCK_EX)
                    601: 	    &&
                    602: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    603: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    604: 	    while (my ($key,$value) = each(%{$newenv})) {
                    605: 	        $disk_env{$key} = $value;
                    606: 	    }
                    607: 	    untie(%disk_env);
1.35      www       608:         }
1.191     harris41  609:     }
1.56      www       610:     return 'ok';
                    611: }
                    612: # ----------------------------------------------------- Delete from Environment
                    613: 
                    614: sub delenv {
1.1104    raeburn   615:     my ($delthis,$regexp,$roles) = @_;
                    616:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    617:         my $refused = 1;
                    618:         if (ref($roles) eq 'ARRAY') {
                    619:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    620:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    621:                 $refused = 0;
                    622:             }
                    623:         }
                    624:         if ($refused) {
                    625:             &logthis("<font color=\"blue\">WARNING: ".
                    626:                      "Attempt to delete from environment ".$delthis);
                    627:             return 'error';
                    628:         }
1.56      www       629:     }
1.917     albertel  630:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    631:     if ($opened
1.915     albertel  632: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  633: 	&&
                    634: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    635: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  636: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   637: 	    if ($regexp) {
                    638:                 if ($key=~/^$delthis/) {
                    639:                     delete($env{$key});
                    640:                     delete($disk_env{$key});
                    641:                 } 
                    642:             } else {
                    643:                 if ($key=~/^\Q$delthis\E/) {
                    644: 		    delete($env{$key});
                    645: 		    delete($disk_env{$key});
                    646: 	        }
                    647:             }
1.448     albertel  648: 	}
1.783     albertel  649: 	untie(%disk_env);
1.5       www       650:     }
                    651:     return 'ok';
1.369     albertel  652: }
                    653: 
1.790     albertel  654: sub get_env_multiple {
                    655:     my ($name) = @_;
                    656:     my @values;
                    657:     if (defined($env{$name})) {
                    658:         # exists is it an array
                    659:         if (ref($env{$name})) {
                    660:             @values=@{ $env{$name} };
                    661:         } else {
                    662:             $values[0]=$env{$name};
                    663:         }
                    664:     }
                    665:     return(@values);
                    666: }
                    667: 
1.958     www       668: # ------------------------------------------------------------------- Locking
                    669: 
                    670: sub set_lock {
                    671:     my ($text)=@_;
                    672:     $locknum++;
                    673:     my $id=$$.'-'.$locknum;
                    674:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    675:              'session.lock.'.$id => $text});
                    676:     return $id;
                    677: }
                    678: 
                    679: sub get_locks {
                    680:     my $num=0;
                    681:     my %texts=();
                    682:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    683:        if ($lock=~/\w/) {
                    684:           $num++;
                    685:           $texts{$lock}=$env{'session.lock.'.$lock};
                    686:        }
                    687:    }
                    688:    return ($num,%texts);
                    689: }
                    690: 
                    691: sub remove_lock {
                    692:     my ($id)=@_;
                    693:     my $newlocks='';
                    694:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    695:        if (($lock=~/\w/) && ($lock ne $id)) {
                    696:           $newlocks.=','.$lock;
                    697:        }
                    698:     }
                    699:     &appenv({'session.locks' => $newlocks});
                    700:     &delenv('session.lock.'.$id);
                    701: }
                    702: 
                    703: sub remove_all_locks {
                    704:     my $activelocks=$env{'session.locks'};
                    705:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    706:        if ($lock=~/\w/) {
                    707:           &remove_lock($lock);
                    708:        }
                    709:     }
                    710: }
                    711: 
                    712: 
1.369     albertel  713: # ------------------------------------------ Find out current server userload
                    714: sub userload {
                    715:     my $numusers=0;
                    716:     {
                    717: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    718: 	my $filename;
                    719: 	my $curtime=time;
                    720: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  721: 	    next if ($filename eq '.' || $filename eq '..');
                    722: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  723: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  724: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  725: 	}
                    726: 	closedir(LONIDS);
                    727:     }
                    728:     my $userloadpercent=0;
                    729:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    730:     if ($maxuserload) {
1.371     albertel  731: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  732:     }
1.372     albertel  733:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  734:     return $userloadpercent;
1.283     www       735: }
                    736: 
1.1       albertel  737: # ------------------------------ Find server with least workload from spare.tab
1.11      www       738: 
1.1       albertel  739: sub spareserver {
1.1083    raeburn   740:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  741:     my $spare_server;
1.370     albertel  742:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  743:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    744:                                                      :  $userloadpercent;
1.1083    raeburn   745:     my ($uint_dom,$remotesessions);
                    746:     if (($udom ne '') && (&domain($udom) ne '')) {
                    747:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    748:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    749:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    750:         $remotesessions = $udomdefaults{'remotesessions'};
                    751:     }
1.784     albertel  752:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   753:         if ($uint_dom) {
                    754:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    755:                                           $try_server));
                    756:         }
1.784     albertel  757: 	($spare_server, $lowest_load) =
                    758: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    759:     }
                    760: 
                    761:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    762: 
                    763:     if (!$found_server) {
                    764: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   765:             if ($uint_dom) {
                    766:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    767:                                              $try_server));
                    768:             }
1.784     albertel  769: 	    ($spare_server, $lowest_load) =
                    770: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    771: 	}
                    772:     }
                    773: 
                    774:     if (!$want_server_name) {
1.968     raeburn   775:         my $protocol = 'http';
                    776:         if ($protocol{$spare_server} eq 'https') {
                    777:             $protocol = $protocol{$spare_server};
                    778:         }
1.1001    raeburn   779:         if (defined($spare_server)) {
                    780:             my $hostname = &hostname($spare_server);
1.1083    raeburn   781:             if (defined($hostname)) {
1.1001    raeburn   782: 	        $spare_server = $protocol.'://'.$hostname;
                    783:             }
                    784:         }
1.784     albertel  785:     }
                    786:     return $spare_server;
                    787: }
                    788: 
                    789: sub compare_server_load {
                    790:     my ($try_server, $spare_server, $lowest_load) = @_;
                    791: 
                    792:     my $loadans     = &reply('load',    $try_server);
                    793:     my $userloadans = &reply('userload',$try_server);
                    794: 
                    795:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072    www       796: 	return; #didn't get a number from the server
1.784     albertel  797:     }
                    798: 
                    799:     my $load;
                    800:     if ($loadans =~ /\d/) {
                    801: 	if ($userloadans =~ /\d/) {
                    802: 	    #both are numbers, pick the bigger one
                    803: 	    $load = ($loadans > $userloadans) ? $loadans 
                    804: 		                              : $userloadans;
1.411     albertel  805: 	} else {
1.784     albertel  806: 	    $load = $loadans;
1.411     albertel  807: 	}
1.784     albertel  808:     } else {
                    809: 	$load = $userloadans;
                    810:     }
                    811: 
                    812:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    813: 	$spare_server = $try_server;
                    814: 	$lowest_load  = $load;
1.370     albertel  815:     }
1.784     albertel  816:     return ($spare_server,$lowest_load);
1.202     matthew   817: }
1.914     albertel  818: 
                    819: # --------------------------- ask offload servers if user already has a session
                    820: sub find_existing_session {
                    821:     my ($udom,$uname) = @_;
                    822:     foreach my $try_server (@{ $spareid{'primary'} },
                    823: 			    @{ $spareid{'default'} }) {
                    824: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    825:     }
                    826:     return;
                    827: }
                    828: 
                    829: # -------------------------------- ask if server already has a session for user
                    830: sub has_user_session {
                    831:     my ($lonid,$udom,$uname) = @_;
                    832:     my $result = &reply(join(':','userhassession',
                    833: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    834:     return 1 if ($result eq 'ok');
                    835: 
                    836:     return 0;
                    837: }
                    838: 
1.1076    raeburn   839: # --------- determine least loaded server in a user's domain which allows login
                    840: 
                    841: sub choose_server {
                    842:     my ($udom) = @_;
                    843:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   844:     my %servers = &get_servers($udom);
1.1076    raeburn   845:     my $lowest_load = 30000;
                    846:     my ($login_host,$hostname);
                    847:     foreach my $lonhost (keys(%servers)) {
                    848:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    849:         if ($loginvia eq '') {
                    850:             ($login_host, $lowest_load) =
                    851:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    852:         }
                    853:     }
                    854:     if ($login_host ne '') {
                    855:         $hostname = $servers{$login_host};
                    856:     }
                    857:     return ($login_host,$hostname);
                    858: }
                    859: 
1.202     matthew   860: # --------------------------------------------- Try to change a user's password
                    861: 
                    862: sub changepass {
1.799     raeburn   863:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   864:     $currentpass = &escape($currentpass);
                    865:     $newpass     = &escape($newpass);
1.1030    raeburn   866:     my $lonhost = $perlvar{'lonHostID'};
                    867:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   868: 		       $server);
                    869:     if (! $answer) {
                    870: 	&logthis("No reply on password change request to $server ".
                    871: 		 "by $uname in domain $udom.");
                    872:     } elsif ($answer =~ "^ok") {
                    873:         &logthis("$uname in $udom successfully changed their password ".
                    874: 		 "on $server.");
                    875:     } elsif ($answer =~ "^pwchange_failure") {
                    876: 	&logthis("$uname in $udom was unable to change their password ".
                    877: 		 "on $server.  The action was blocked by either lcpasswd ".
                    878: 		 "or pwchange");
                    879:     } elsif ($answer =~ "^non_authorized") {
                    880:         &logthis("$uname in $udom did not get their password correct when ".
                    881: 		 "attempting to change it on $server.");
                    882:     } elsif ($answer =~ "^auth_mode_error") {
                    883:         &logthis("$uname in $udom attempted to change their password despite ".
                    884: 		 "not being locally or internally authenticated on $server.");
                    885:     } elsif ($answer =~ "^unknown_user") {
                    886:         &logthis("$uname in $udom attempted to change their password ".
                    887: 		 "on $server but were unable to because $server is not ".
                    888: 		 "their home server.");
                    889:     } elsif ($answer =~ "^refused") {
                    890: 	&logthis("$server refused to change $uname in $udom password because ".
                    891: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   892:     } elsif ($answer =~ "invalid_client") {
                    893:         &logthis("$server refused to change $uname in $udom password because ".
                    894:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   895:     }
                    896:     return $answer;
1.1       albertel  897: }
                    898: 
1.169     harris41  899: # ----------------------- Try to determine user's current authentication scheme
                    900: 
                    901: sub queryauthenticate {
                    902:     my ($uname,$udom)=@_;
1.456     albertel  903:     my $uhome=&homeserver($uname,$udom);
                    904:     if (!$uhome) {
                    905: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    906: 	return 'no_host';
                    907:     }
                    908:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    909:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    910: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  911:     }
1.456     albertel  912:     return $answer;
1.169     harris41  913: }
                    914: 
1.1       albertel  915: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       916: 
1.1       albertel  917: sub authenticate {
1.1073    raeburn   918:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  919:     $upass=&escape($upass);
                    920:     $uname= &LONCAPA::clean_username($uname);
1.836     www       921:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   922:     my $newhome;
1.836     www       923:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    924: # Maybe the machine was offline and only re-appeared again recently?
                    925:         &reconlonc();
                    926: # One more
1.952     raeburn   927: 	$uhome=&homeserver($uname,$udom,1);
                    928:         if (($uhome eq 'no_host') && $checkdefauth) {
                    929:             if (defined(&domain($udom,'primary'))) {
                    930:                 $newhome=&domain($udom,'primary');
                    931:             }
                    932:             if ($newhome ne '') {
                    933:                 $uhome = $newhome;
                    934:             }
                    935:         }
1.836     www       936: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    937: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   938: 	    return 'no_host';
                    939:         }
1.1       albertel  940:     }
1.1073    raeburn   941:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  942:     if ($answer eq 'authorized') {
1.952     raeburn   943:         if ($newhome) {
                    944:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    945:             return 'no_account_on_host'; 
                    946:         } else {
                    947:             &logthis("User $uname at $udom authorized by $uhome");
                    948:             return $uhome;
                    949:         }
1.471     albertel  950:     }
                    951:     if ($answer eq 'non_authorized') {
                    952: 	&logthis("User $uname at $udom rejected by $uhome");
                    953: 	return 'no_host'; 
1.9       www       954:     }
1.471     albertel  955:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  956:     return 'no_host';
                    957: }
                    958: 
1.1073    raeburn   959: sub can_host_session {
1.1074    raeburn   960:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   961:     my $canhost = 1;
1.1074    raeburn   962:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   963:     if (ref($remotesessions) eq 'HASH') {
                    964:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   965:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   966:                 $canhost = 0;
                    967:             } else {
                    968:                 $canhost = 1;
                    969:             }
                    970:         }
                    971:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   972:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   973:                 $canhost = 1;
                    974:             } else {
                    975:                 $canhost = 0;
                    976:             }
                    977:         }
                    978:         if ($canhost) {
                    979:             if ($remotesessions->{'version'} ne '') {
                    980:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    981:                 if ($reqmajor ne '' && $reqminor ne '') {
                    982:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    983:                         my $major = $1;
                    984:                         my $minor = $2;
                    985:                         if (($major < $reqmajor ) ||
                    986:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    987:                             $canhost = 0;
                    988:                         }
                    989:                     } else {
                    990:                         $canhost = 0;
                    991:                     }
                    992:                 }
                    993:             }
                    994:         }
                    995:     }
                    996:     if ($canhost) {
                    997:         if (ref($hostedsessions) eq 'HASH') {
                    998:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    999:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1000:                     $canhost = 0;
                   1001:                 } else {
                   1002:                     $canhost = 1;
                   1003:                 }
                   1004:             }
                   1005:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1006:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1007:                     $canhost = 1;
                   1008:                 } else {
                   1009:                     $canhost = 0;
                   1010:                 }
                   1011:             }
                   1012:         }
                   1013:     }
                   1014:     return $canhost;
                   1015: }
                   1016: 
1.1083    raeburn  1017: sub spare_can_host {
                   1018:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1019:     my $canhost=1;
                   1020:     my @intdoms;
                   1021:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1022:     if (ref($internet_names) eq 'ARRAY') {
                   1023:         @intdoms = @{$internet_names};
                   1024:     }
                   1025:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1026:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1027:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1028:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1029:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1030:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1031:                                      $remotesessions,
                   1032:                                      $defdomdefaults{'hostedsessions'});
                   1033:     }
                   1034:     return $canhost;
                   1035: }
                   1036: 
1.1       albertel 1037: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1038: 
1.599     albertel 1039: my %homecache;
1.1       albertel 1040: sub homeserver {
1.230     stredwic 1041:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1042:     my $index="$uname:$udom";
1.426     albertel 1043: 
1.599     albertel 1044:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1045: 
                   1046:     my %servers = &get_servers($udom,'library');
                   1047:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1048:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1049: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1050: 
                   1051: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1052: 	if ($answer eq 'found') {
                   1053: 	    delete($badServerCache{$tryserver}); 
                   1054: 	    return $homecache{$index}=$tryserver;
                   1055: 	} elsif ($answer eq 'no_host') {
                   1056: 	    $badServerCache{$tryserver}=1;
                   1057: 	}
1.1       albertel 1058:     }    
                   1059:     return 'no_host';
1.70      www      1060: }
                   1061: 
                   1062: # ------------------------------------- Find the usernames behind a list of IDs
                   1063: 
                   1064: sub idget {
                   1065:     my ($udom,@ids)=@_;
                   1066:     my %returnhash=();
                   1067:     
1.841     albertel 1068:     my %servers = &get_servers($udom,'library');
                   1069:     foreach my $tryserver (keys(%servers)) {
                   1070: 	my $idlist=join('&',@ids);
                   1071: 	$idlist=~tr/A-Z/a-z/; 
                   1072: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1073: 	my @answer=();
                   1074: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1075: 	    @answer=split(/\&/,$reply);
                   1076: 	}                    ;
                   1077: 	my $i;
                   1078: 	for ($i=0;$i<=$#ids;$i++) {
                   1079: 	    if ($answer[$i]) {
                   1080: 		$returnhash{$ids[$i]}=$answer[$i];
                   1081: 	    } 
                   1082: 	}
                   1083:     } 
1.70      www      1084:     return %returnhash;
                   1085: }
                   1086: 
                   1087: # ------------------------------------- Find the IDs behind a list of usernames
                   1088: 
                   1089: sub idrget {
                   1090:     my ($udom,@unames)=@_;
                   1091:     my %returnhash=();
1.800     albertel 1092:     foreach my $uname (@unames) {
                   1093:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1094:     }
1.70      www      1095:     return %returnhash;
                   1096: }
                   1097: 
                   1098: # ------------------------------- Store away a list of names and associated IDs
                   1099: 
                   1100: sub idput {
                   1101:     my ($udom,%ids)=@_;
                   1102:     my %servers=();
1.800     albertel 1103:     foreach my $uname (keys(%ids)) {
                   1104: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1105:         my $uhom=&homeserver($uname,$udom);
1.70      www      1106:         if ($uhom ne 'no_host') {
1.800     albertel 1107:             my $id=&escape($ids{$uname});
1.70      www      1108:             $id=~tr/A-Z/a-z/;
1.800     albertel 1109:             my $esc_unam=&escape($uname);
1.70      www      1110: 	    if ($servers{$uhom}) {
1.800     albertel 1111: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1112:             } else {
1.800     albertel 1113:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1114:             }
                   1115:         }
1.191     harris41 1116:     }
1.800     albertel 1117:     foreach my $server (keys(%servers)) {
                   1118:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1119:     }
1.344     www      1120: }
                   1121: 
1.1023    raeburn  1122: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1123: sub dump_dom {
1.1023    raeburn  1124:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1125:     if (!$udom) {
                   1126:         $udom=$env{'user.domain'};
                   1127:     }
                   1128:     my %returnhash;
1.1023    raeburn  1129:     if ($udom) {
                   1130:         my $uname = &get_domainconfiguser($udom);
                   1131:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1132:     }
                   1133:     return %returnhash;
                   1134: }
                   1135: 
1.1023    raeburn  1136: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1137: 
                   1138: sub get_dom {
1.860     raeburn  1139:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1140:     my $items='';
                   1141:     foreach my $item (@$storearr) {
                   1142:         $items.=&escape($item).'&';
                   1143:     }
                   1144:     $items=~s/\&$//;
1.860     raeburn  1145:     if (!$udom) {
                   1146:         $udom=$env{'user.domain'};
                   1147:         if (defined(&domain($udom,'primary'))) {
                   1148:             $uhome=&domain($udom,'primary');
                   1149:         } else {
1.874     albertel 1150:             undef($uhome);
1.860     raeburn  1151:         }
                   1152:     } else {
                   1153:         if (!$uhome) {
                   1154:             if (defined(&domain($udom,'primary'))) {
                   1155:                 $uhome=&domain($udom,'primary');
                   1156:             }
                   1157:         }
                   1158:     }
                   1159:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1160:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1161:         my %returnhash;
1.875     albertel 1162:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1163:             return %returnhash;
                   1164:         }
1.806     raeburn  1165:         my @pairs=split(/\&/,$rep);
                   1166:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1167:             return @pairs;
                   1168:         }
                   1169:         my $i=0;
                   1170:         foreach my $item (@$storearr) {
                   1171:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1172:             $i++;
                   1173:         }
                   1174:         return %returnhash;
                   1175:     } else {
1.880     banghart 1176:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1177:     }
                   1178: }
                   1179: 
                   1180: # -------------------------------------------- put items in domain db files 
                   1181: 
                   1182: sub put_dom {
1.860     raeburn  1183:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1184:     if (!$udom) {
                   1185:         $udom=$env{'user.domain'};
                   1186:         if (defined(&domain($udom,'primary'))) {
                   1187:             $uhome=&domain($udom,'primary');
                   1188:         } else {
1.874     albertel 1189:             undef($uhome);
1.860     raeburn  1190:         }
                   1191:     } else {
                   1192:         if (!$uhome) {
                   1193:             if (defined(&domain($udom,'primary'))) {
                   1194:                 $uhome=&domain($udom,'primary');
                   1195:             }
                   1196:         }
                   1197:     } 
                   1198:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1199:         my $items='';
                   1200:         foreach my $item (keys(%$storehash)) {
                   1201:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1202:         }
                   1203:         $items=~s/\&$//;
                   1204:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1205:     } else {
1.860     raeburn  1206:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1207:     }
                   1208: }
                   1209: 
1.1023    raeburn  1210: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1211: sub newput_dom {
1.1023    raeburn  1212:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1213:     my $result;
                   1214:     if (!$udom) {
                   1215:         $udom=$env{'user.domain'};
                   1216:     }
1.1023    raeburn  1217:     if ($udom) {
                   1218:         my $uname = &get_domainconfiguser($udom);
                   1219:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1220:     }
                   1221:     return $result;
                   1222: }
                   1223: 
1.1023    raeburn  1224: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1225: sub del_dom {
1.1023    raeburn  1226:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1227:     if (ref($storearr) eq 'ARRAY') {
                   1228:         if (!$udom) {
                   1229:             $udom=$env{'user.domain'};
                   1230:         }
1.1023    raeburn  1231:         if ($udom) {
                   1232:             my $uname = &get_domainconfiguser($udom); 
                   1233:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1234:         }
                   1235:     }
                   1236: }
                   1237: 
1.1023    raeburn  1238: # ----------------------------------construct domainconfig user for a domain 
                   1239: sub get_domainconfiguser {
                   1240:     my ($udom) = @_;
                   1241:     return $udom.'-domainconfig';
                   1242: }
                   1243: 
1.837     raeburn  1244: sub retrieve_inst_usertypes {
                   1245:     my ($udom) = @_;
                   1246:     my (%returnhash,@order);
1.989     raeburn  1247:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1248:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1249:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1250:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1251:         @order = @{$domdefs{'inststatusorder'}};
                   1252:     } else {
                   1253:         if (defined(&domain($udom,'primary'))) {
                   1254:             my $uhome=&domain($udom,'primary');
                   1255:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1256:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1257:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1258:                 return (\%returnhash,\@order);
                   1259:             }
                   1260:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1261:             my @pairs=split(/\&/,$hashitems);
                   1262:             foreach my $item (@pairs) {
                   1263:                 my ($key,$value)=split(/=/,$item,2);
                   1264:                 $key = &unescape($key);
                   1265:                 next if ($key =~ /^error: 2 /);
                   1266:                 $returnhash{$key}=&thaw_unescape($value);
                   1267:             }
                   1268:             my @esc_order = split(/\&/,$orderitems);
                   1269:             foreach my $item (@esc_order) {
                   1270:                 push(@order,&unescape($item));
                   1271:             }
                   1272:         } else {
                   1273:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1274:         }
                   1275:     }
                   1276:     return (\%returnhash,\@order);
                   1277: }
                   1278: 
1.868     raeburn  1279: sub is_domainimage {
                   1280:     my ($url) = @_;
                   1281:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1282:         if (&domain($1) ne '') {
                   1283:             return '1';
                   1284:         }
                   1285:     }
                   1286:     return;
                   1287: }
                   1288: 
1.899     raeburn  1289: sub inst_directory_query {
                   1290:     my ($srch) = @_;
                   1291:     my $udom = $srch->{'srchdomain'};
                   1292:     my %results;
                   1293:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1294:     my $outcome;
1.899     raeburn  1295:     if ($homeserver ne '') {
1.904     albertel 1296: 	my $queryid=&reply("querysend:instdirsearch:".
                   1297: 			   &escape($srch->{'srchby'}).':'.
                   1298: 			   &escape($srch->{'srchterm'}).':'.
                   1299: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1300: 	my $host=&hostname($homeserver);
                   1301: 	if ($queryid !~/^\Q$host\E\_/) {
                   1302: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1303: 	    return;
                   1304: 	}
                   1305: 	my $response = &get_query_reply($queryid);
                   1306: 	my $maxtries = 5;
                   1307: 	my $tries = 1;
                   1308: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1309: 	    $response = &get_query_reply($queryid);
                   1310: 	    $tries ++;
                   1311: 	}
                   1312: 
                   1313:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1314:             if ($response eq 'unavailable') {
                   1315:                 $outcome = $response;
                   1316:             } else {
                   1317:                 $outcome = 'ok';
                   1318:                 my @matches = split(/\n/,$response);
                   1319:                 foreach my $match (@matches) {
                   1320:                     my ($key,$value) = split(/=/,$match);
                   1321:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1322:                 }
1.899     raeburn  1323:             }
                   1324:         }
                   1325:     }
1.909     raeburn  1326:     return ($outcome,%results);
1.899     raeburn  1327: }
                   1328: 
                   1329: sub usersearch {
                   1330:     my ($srch) = @_;
                   1331:     my $dom = $srch->{'srchdomain'};
                   1332:     my %results;
                   1333:     my %libserv = &all_library();
                   1334:     my $query = 'usersearch';
                   1335:     foreach my $tryserver (keys(%libserv)) {
                   1336:         if (&host_domain($tryserver) eq $dom) {
                   1337:             my $host=&hostname($tryserver);
                   1338:             my $queryid=
1.911     raeburn  1339:                 &reply("querysend:".&escape($query).':'.
                   1340:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1341:                        &escape($srch->{'srchtype'}).':'.
                   1342:                        &escape($srch->{'srchterm'}),$tryserver);
                   1343:             if ($queryid !~/^\Q$host\E\_/) {
                   1344:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1345:                 next;
1.899     raeburn  1346:             }
                   1347:             my $reply = &get_query_reply($queryid);
                   1348:             my $maxtries = 1;
                   1349:             my $tries = 1;
                   1350:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1351:                 $reply = &get_query_reply($queryid);
                   1352:                 $tries ++;
                   1353:             }
                   1354:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1355:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1356:             } else {
1.911     raeburn  1357:                 my @matches;
                   1358:                 if ($reply =~ /\n/) {
                   1359:                     @matches = split(/\n/,$reply);
                   1360:                 } else {
                   1361:                     @matches = split(/\&/,$reply);
                   1362:                 }
1.899     raeburn  1363:                 foreach my $match (@matches) {
                   1364:                     my ($uname,$udom,%userhash);
1.911     raeburn  1365:                     foreach my $entry (split(/:/,$match)) {
                   1366:                         my ($key,$value) =
                   1367:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1368:                         $userhash{$key} = $value;
                   1369:                         if ($key eq 'username') {
                   1370:                             $uname = $value;
                   1371:                         } elsif ($key eq 'domain') {
                   1372:                             $udom = $value;
1.911     raeburn  1373:                         }
1.899     raeburn  1374:                     }
                   1375:                     $results{$uname.':'.$udom} = \%userhash;
                   1376:                 }
                   1377:             }
                   1378:         }
                   1379:     }
                   1380:     return %results;
                   1381: }
                   1382: 
1.912     raeburn  1383: sub get_instuser {
                   1384:     my ($udom,$uname,$id) = @_;
                   1385:     my $homeserver = &domain($udom,'primary');
                   1386:     my ($outcome,%results);
                   1387:     if ($homeserver ne '') {
                   1388:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1389:                            &escape($id).':'.&escape($udom),$homeserver);
                   1390:         my $host=&hostname($homeserver);
                   1391:         if ($queryid !~/^\Q$host\E\_/) {
                   1392:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1393:             return;
                   1394:         }
                   1395:         my $response = &get_query_reply($queryid);
                   1396:         my $maxtries = 5;
                   1397:         my $tries = 1;
                   1398:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1399:             $response = &get_query_reply($queryid);
                   1400:             $tries ++;
                   1401:         }
                   1402:         if (!&error($response) && $response ne 'refused') {
                   1403:             if ($response eq 'unavailable') {
                   1404:                 $outcome = $response;
                   1405:             } else {
                   1406:                 $outcome = 'ok';
                   1407:                 my @matches = split(/\n/,$response);
                   1408:                 foreach my $match (@matches) {
                   1409:                     my ($key,$value) = split(/=/,$match);
                   1410:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1411:                 }
                   1412:             }
                   1413:         }
                   1414:     }
                   1415:     my %userinfo;
                   1416:     if (ref($results{$uname}) eq 'HASH') {
                   1417:         %userinfo = %{$results{$uname}};
                   1418:     } 
                   1419:     return ($outcome,%userinfo);
                   1420: }
                   1421: 
                   1422: sub inst_rulecheck {
1.923     raeburn  1423:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1424:     my %returnhash;
                   1425:     if ($udom ne '') {
                   1426:         if (ref($rules) eq 'ARRAY') {
                   1427:             @{$rules} = map {&escape($_);} (@{$rules});
                   1428:             my $rulestr = join(':',@{$rules});
                   1429:             my $homeserver=&domain($udom,'primary');
                   1430:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1431:                 my $response;
                   1432:                 if ($item eq 'username') {                
                   1433:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1434:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1435:                                               $homeserver));
1.923     raeburn  1436:                 } elsif ($item eq 'id') {
                   1437:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1438:                                               ':'.&escape($id).':'.$rulestr,
                   1439:                                               $homeserver));
1.945     raeburn  1440:                 } elsif ($item eq 'selfcreate') {
                   1441:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1442:                                                &escape($udom).':'.&escape($uname).
                   1443:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1444:                 }
1.912     raeburn  1445:                 if ($response ne 'refused') {
                   1446:                     my @pairs=split(/\&/,$response);
                   1447:                     foreach my $item (@pairs) {
                   1448:                         my ($key,$value)=split(/=/,$item,2);
                   1449:                         $key = &unescape($key);
                   1450:                         next if ($key =~ /^error: 2 /);
                   1451:                         $returnhash{$key}=&thaw_unescape($value);
                   1452:                     }
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     return %returnhash;
                   1458: }
                   1459: 
                   1460: sub inst_userrules {
1.923     raeburn  1461:     my ($udom,$check) = @_;
1.912     raeburn  1462:     my (%ruleshash,@ruleorder);
                   1463:     if ($udom ne '') {
                   1464:         my $homeserver=&domain($udom,'primary');
                   1465:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1466:             my $response;
                   1467:             if ($check eq 'id') {
                   1468:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1469:                                  $homeserver);
1.943     raeburn  1470:             } elsif ($check eq 'email') {
                   1471:                 $response=&reply('instemailrules:'.&escape($udom),
                   1472:                                  $homeserver);
1.923     raeburn  1473:             } else {
                   1474:                 $response=&reply('instuserrules:'.&escape($udom),
                   1475:                                  $homeserver);
                   1476:             }
1.912     raeburn  1477:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1478:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1479:                 ($response ne 'no_such_host')) {
                   1480:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1481:                 my @pairs=split(/\&/,$hashitems);
                   1482:                 foreach my $item (@pairs) {
                   1483:                     my ($key,$value)=split(/=/,$item,2);
                   1484:                     $key = &unescape($key);
                   1485:                     next if ($key =~ /^error: 2 /);
                   1486:                     $ruleshash{$key}=&thaw_unescape($value);
                   1487:                 }
                   1488:                 my @esc_order = split(/\&/,$orderitems);
                   1489:                 foreach my $item (@esc_order) {
                   1490:                     push(@ruleorder,&unescape($item));
                   1491:                 }
                   1492:             }
                   1493:         }
                   1494:     }
                   1495:     return (\%ruleshash,\@ruleorder);
                   1496: }
                   1497: 
1.976     raeburn  1498: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1499: 
                   1500: sub get_domain_defaults {
                   1501:     my ($domain) = @_;
                   1502:     my $cachetime = 60*60*24;
                   1503:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1504:     if (defined($cached)) {
                   1505:         if (ref($result) eq 'HASH') {
                   1506:             return %{$result};
                   1507:         }
                   1508:     }
                   1509:     my %domdefaults;
                   1510:     my %domconfig =
1.989     raeburn  1511:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1512:                                   'requestcourses','inststatus',
1.1073    raeburn  1513:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1514:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1515:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1516:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1517:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1518:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1519:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1520:     } else {
                   1521:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1522:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1523:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1524:     }
1.976     raeburn  1525:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1526:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1527:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1528:         } else {
                   1529:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1530:         } 
                   1531:         my @usertools = ('aboutme','blog','portfolio');
                   1532:         foreach my $item (@usertools) {
                   1533:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1534:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1535:             }
                   1536:         }
                   1537:     }
1.985     raeburn  1538:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1539:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1540:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1541:         }
                   1542:     }
1.989     raeburn  1543:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1544:         foreach my $item ('inststatustypes','inststatusorder') {
                   1545:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1546:         }
                   1547:     }
1.1047    raeburn  1548:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1549:         foreach my $item ('canuse_pdfforms') {
                   1550:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1551:         }
                   1552:     }
1.1073    raeburn  1553:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1554:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1555:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1556:         }
                   1557:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1558:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1559:         }
                   1560:     }
1.943     raeburn  1561:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1562:                                   $cachetime);
                   1563:     return %domdefaults;
                   1564: }
                   1565: 
1.344     www      1566: # --------------------------------------------------- Assign a key to a student
                   1567: 
                   1568: sub assign_access_key {
1.364     www      1569: #
                   1570: # a valid key looks like uname:udom#comments
                   1571: # comments are being appended
                   1572: #
1.498     www      1573:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1574:     $kdom=
1.620     albertel 1575:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1576:     $knum=
1.620     albertel 1577:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1578:     $cdom=
1.620     albertel 1579:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1580:     $cnum=
1.620     albertel 1581:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1582:     $udom=$env{'user.name'} unless (defined($udom));
                   1583:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1584:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1585:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1586:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1587:                                                   # assigned to this person
                   1588:                                                   # - this should not happen,
1.345     www      1589:                                                   # unless something went wrong
                   1590:                                                   # the first time around
                   1591: # ready to assign
1.364     www      1592:         $logentry=$1.'; '.$logentry;
1.496     www      1593:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1594:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1595: # key now belongs to user
1.346     www      1596: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1597:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1598:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1599:                 return 'ok';
                   1600:             } else {
                   1601:                 return 
                   1602:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1603: 	    }
                   1604:         } else {
                   1605:             return 'error: Could not assign key, try again later.';
                   1606:         }
1.364     www      1607:     } elsif (!$existing{$ckey}) {
1.345     www      1608: # the key does not exist
                   1609: 	return 'error: The key does not exist';
                   1610:     } else {
                   1611: # the key is somebody else's
                   1612: 	return 'error: The key is already in use';
                   1613:     }
1.344     www      1614: }
                   1615: 
1.364     www      1616: # ------------------------------------------ put an additional comment on a key
                   1617: 
                   1618: sub comment_access_key {
                   1619: #
                   1620: # a valid key looks like uname:udom#comments
                   1621: # comments are being appended
                   1622: #
                   1623:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1624:     $cdom=
1.620     albertel 1625:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1626:     $cnum=
1.620     albertel 1627:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1628:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1629:     if ($existing{$ckey}) {
                   1630:         $existing{$ckey}.='; '.$logentry;
                   1631: # ready to assign
1.367     www      1632:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1633:                                                  $cdom,$cnum) eq 'ok') {
                   1634: 	    return 'ok';
                   1635:         } else {
                   1636: 	    return 'error: Count not store comment.';
                   1637:         }
                   1638:     } else {
                   1639: # the key does not exist
                   1640: 	return 'error: The key does not exist';
                   1641:     }
                   1642: }
                   1643: 
1.344     www      1644: # ------------------------------------------------------ Generate a set of keys
                   1645: 
                   1646: sub generate_access_keys {
1.364     www      1647:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1648:     $cdom=
1.620     albertel 1649:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1650:     $cnum=
1.620     albertel 1651:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1652:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1653:     unless (($cdom) && ($cnum)) { return 0; }
                   1654:     if ($number>10000) { return 0; }
                   1655:     sleep(2); # make sure don't get same seed twice
                   1656:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1657:     my $total=0;
                   1658:     for (my $i=1;$i<=$number;$i++) {
                   1659:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1660:                   sprintf("%lx",int(100000*rand)).'-'.
                   1661:                   sprintf("%lx",int(100000*rand));
                   1662:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1663:        $newkey=~s/0/h/g; # and also 0 and O
                   1664:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1665:        if ($existing{$newkey}) {
                   1666:            $i--;
                   1667:        } else {
1.364     www      1668: 	  if (&put('accesskeys',
                   1669:               { $newkey => '# generated '.localtime().
1.620     albertel 1670:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1671:                            '; '.$logentry },
                   1672: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1673:               $total++;
                   1674: 	  }
                   1675:        }
                   1676:     }
1.620     albertel 1677:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1678:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1679:     return $total;
                   1680: }
                   1681: 
                   1682: # ------------------------------------------------------- Validate an accesskey
                   1683: 
                   1684: sub validate_access_key {
                   1685:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1686:     $cdom=
1.620     albertel 1687:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1688:     $cnum=
1.620     albertel 1689:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1690:     $udom=$env{'user.domain'} unless (defined($udom));
                   1691:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1692:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1693:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1694: }
                   1695: 
                   1696: # ------------------------------------- Find the section of student in a course
1.652     albertel 1697: sub devalidate_getsection_cache {
                   1698:     my ($udom,$unam,$courseid)=@_;
                   1699:     my $hashid="$udom:$unam:$courseid";
                   1700:     &devalidate_cache_new('getsection',$hashid);
                   1701: }
1.298     matthew  1702: 
1.815     albertel 1703: sub courseid_to_courseurl {
                   1704:     my ($courseid) = @_;
                   1705:     #already url style courseid
                   1706:     return $courseid if ($courseid =~ m{^/});
                   1707: 
                   1708:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1709: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1710: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1711: 	return "/$cdom/$cnum";
                   1712:     }
                   1713: 
                   1714:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1715:     if (exists($courseinfo{'num'})) {
                   1716: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1717:     }
                   1718: 
                   1719:     return undef;
                   1720: }
                   1721: 
1.298     matthew  1722: sub getsection {
                   1723:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1724:     my $cachetime=1800;
1.551     albertel 1725: 
                   1726:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1727:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1728:     if (defined($cached)) { return $result; }
                   1729: 
1.298     matthew  1730:     my %Pending; 
                   1731:     my %Expired;
                   1732:     #
                   1733:     # Each role can either have not started yet (pending), be active, 
                   1734:     #    or have expired.
                   1735:     #
                   1736:     # If there is an active role, we are done.
                   1737:     #
                   1738:     # If there is more than one role which has not started yet, 
                   1739:     #     choose the one which will start sooner
                   1740:     # If there is one role which has not started yet, return it.
                   1741:     #
                   1742:     # If there is more than one expired role, choose the one which ended last.
                   1743:     # If there is a role which has expired, return it.
                   1744:     #
1.815     albertel 1745:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1746:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1747:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1748:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1749:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1750:         my $section=$1;
                   1751:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1752:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1753:         my $now=time;
1.548     albertel 1754:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1755:             $Expired{$end}=$section;
                   1756:             next;
                   1757:         }
1.548     albertel 1758:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1759:             $Pending{$start}=$section;
                   1760:             next;
                   1761:         }
1.599     albertel 1762:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1763:     }
                   1764:     #
                   1765:     # Presumedly there will be few matching roles from the above
                   1766:     # loop and the sorting time will be negligible.
                   1767:     if (scalar(keys(%Pending))) {
                   1768:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1769:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1770:     } 
                   1771:     if (scalar(keys(%Expired))) {
                   1772:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1773:         my $time = pop(@sorted);
1.599     albertel 1774:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1775:     }
1.599     albertel 1776:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1777: }
1.70      www      1778: 
1.599     albertel 1779: sub save_cache {
                   1780:     &purge_remembered();
1.722     albertel 1781:     #&Apache::loncommon::validate_page();
1.620     albertel 1782:     undef(%env);
1.780     albertel 1783:     undef($env_loaded);
1.599     albertel 1784: }
1.452     albertel 1785: 
1.599     albertel 1786: my $to_remember=-1;
                   1787: my %remembered;
                   1788: my %accessed;
                   1789: my $kicks=0;
                   1790: my $hits=0;
1.849     albertel 1791: sub make_key {
                   1792:     my ($name,$id) = @_;
1.872     albertel 1793:     if (length($id) > 65 
                   1794: 	&& length(&escape($id)) > 200) {
                   1795: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1796:     }
1.849     albertel 1797:     return &escape($name.':'.$id);
                   1798: }
                   1799: 
1.599     albertel 1800: sub devalidate_cache_new {
                   1801:     my ($name,$id,$debug) = @_;
                   1802:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1803:     $id=&make_key($name,$id);
1.599     albertel 1804:     $memcache->delete($id);
                   1805:     delete($remembered{$id});
                   1806:     delete($accessed{$id});
                   1807: }
                   1808: 
                   1809: sub is_cached_new {
                   1810:     my ($name,$id,$debug) = @_;
1.849     albertel 1811:     $id=&make_key($name,$id);
1.599     albertel 1812:     if (exists($remembered{$id})) {
                   1813: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1814: 	$accessed{$id}=[&gettimeofday()];
                   1815: 	$hits++;
                   1816: 	return ($remembered{$id},1);
                   1817:     }
                   1818:     my $value = $memcache->get($id);
                   1819:     if (!(defined($value))) {
                   1820: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1821: 	return (undef,undef);
1.416     albertel 1822:     }
1.599     albertel 1823:     if ($value eq '__undef__') {
                   1824: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1825: 	$value=undef;
                   1826:     }
                   1827:     &make_room($id,$value,$debug);
                   1828:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1829:     return ($value,1);
                   1830: }
                   1831: 
                   1832: sub do_cache_new {
                   1833:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1834:     $id=&make_key($name,$id);
1.599     albertel 1835:     my $setvalue=$value;
                   1836:     if (!defined($setvalue)) {
                   1837: 	$setvalue='__undef__';
                   1838:     }
1.623     albertel 1839:     if (!defined($time) ) {
                   1840: 	$time=600;
                   1841:     }
1.599     albertel 1842:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1843:     my $result = $memcache->set($id,$setvalue,$time);
                   1844:     if (! $result) {
1.872     albertel 1845: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1846: 	$memcache->disconnect_all();
1.872     albertel 1847:     }
1.600     albertel 1848:     # need to make a copy of $value
1.919     albertel 1849:     &make_room($id,$value,$debug);
1.599     albertel 1850:     return $value;
                   1851: }
                   1852: 
                   1853: sub make_room {
                   1854:     my ($id,$value,$debug)=@_;
1.919     albertel 1855: 
                   1856:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1857:                                     : $value;
1.599     albertel 1858:     if ($to_remember<0) { return; }
                   1859:     $accessed{$id}=[&gettimeofday()];
                   1860:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1861:     my $to_kick;
                   1862:     my $max_time=0;
                   1863:     foreach my $other (keys(%accessed)) {
                   1864: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1865: 	    $to_kick=$other;
                   1866: 	    $max_time=&tv_interval($accessed{$other});
                   1867: 	}
                   1868:     }
                   1869:     delete($remembered{$to_kick});
                   1870:     delete($accessed{$to_kick});
                   1871:     $kicks++;
                   1872:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1873:     return;
                   1874: }
                   1875: 
1.599     albertel 1876: sub purge_remembered {
1.604     albertel 1877:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1878:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1879:     undef(%remembered);
                   1880:     undef(%accessed);
1.428     albertel 1881: }
1.70      www      1882: # ------------------------------------- Read an entry from a user's environment
                   1883: 
                   1884: sub userenvironment {
                   1885:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1886:     my $items;
                   1887:     foreach my $item (@what) {
                   1888:         $items.=&escape($item).'&';
                   1889:     }
                   1890:     $items=~s/\&$//;
1.70      www      1891:     my %returnhash=();
1.1009    raeburn  1892:     my $uhome = &homeserver($unam,$udom);
                   1893:     unless ($uhome eq 'no_host') {
                   1894:         my @answer=split(/\&/, 
                   1895:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1896:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1897:             return %returnhash;
                   1898:         }
1.1009    raeburn  1899:         my $i;
                   1900:         for ($i=0;$i<=$#what;$i++) {
                   1901: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1902:         }
1.70      www      1903:     }
                   1904:     return %returnhash;
1.1       albertel 1905: }
                   1906: 
1.617     albertel 1907: # ---------------------------------------------------------- Get a studentphoto
                   1908: sub studentphoto {
                   1909:     my ($udom,$unam,$ext) = @_;
                   1910:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1911:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1912:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1913:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1914:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1915:             } else {
                   1916:                 my ($result,$perm_reqd)=
1.707     albertel 1917: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1918:                 if ($result eq 'ok') {
                   1919:                     if (!($perm_reqd eq 'yes')) {
                   1920:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1921:                     }
                   1922:                 }
                   1923:             }
                   1924:         }
                   1925:     } else {
                   1926:         my ($result,$perm_reqd) = 
1.707     albertel 1927: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1928:         if ($result eq 'ok') {
                   1929:             if (!($perm_reqd eq 'yes')) {
                   1930:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1931:             }
                   1932:         }
                   1933:     }
                   1934:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1935: }
                   1936: 
                   1937: sub retrievestudentphoto {
                   1938:     my ($udom,$unam,$ext,$type) = @_;
                   1939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1940:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1941:     if ($ret eq 'ok') {
                   1942:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1943:         if ($type eq 'thumbnail') {
                   1944:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1945:         }
                   1946:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1947:         return $tokenurl;
                   1948:     } else {
                   1949:         if ($type eq 'thumbnail') {
                   1950:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1951:         } else { 
                   1952:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1953:         }
1.617     albertel 1954:     }
                   1955: }
                   1956: 
1.263     www      1957: # -------------------------------------------------------------------- New chat
                   1958: 
                   1959: sub chatsend {
1.724     raeburn  1960:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1961:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1962:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1963:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1964:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1965: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1966: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1967: }
                   1968: 
                   1969: # ------------------------------------------ Find current version of a resource
                   1970: 
                   1971: sub getversion {
                   1972:     my $fname=&clutter(shift);
                   1973:     unless ($fname=~/^\/res\//) { return -1; }
                   1974:     return &currentversion(&filelocation('',$fname));
                   1975: }
                   1976: 
                   1977: sub currentversion {
                   1978:     my $fname=shift;
1.599     albertel 1979:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1980:     if (defined($cached)) { return $result; }
1.292     www      1981:     my $author=$fname;
                   1982:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1983:     my ($udom,$uname)=split(/\//,$author);
                   1984:     my $home=homeserver($uname,$udom);
                   1985:     if ($home eq 'no_host') { 
                   1986:         return -1; 
                   1987:     }
                   1988:     my $answer=reply("currentversion:$fname",$home);
                   1989:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1990: 	return -1;
                   1991:     }
1.599     albertel 1992:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1993: }
                   1994: 
1.1       albertel 1995: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1996: 
1.1       albertel 1997: sub subscribe {
                   1998:     my $fname=shift;
1.761     raeburn  1999:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2000:     $fname=~s/[\n\r]//g;
1.1       albertel 2001:     my $author=$fname;
                   2002:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2003:     my ($udom,$uname)=split(/\//,$author);
                   2004:     my $home=homeserver($uname,$udom);
1.335     albertel 2005:     if ($home eq 'no_host') {
                   2006:         return 'not_found';
1.1       albertel 2007:     }
                   2008:     my $answer=reply("sub:$fname",$home);
1.64      www      2009:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2010: 	$answer.=' by '.$home;
                   2011:     }
1.1       albertel 2012:     return $answer;
                   2013: }
                   2014:     
1.8       www      2015: # -------------------------------------------------------------- Replicate file
                   2016: 
                   2017: sub repcopy {
                   2018:     my $filename=shift;
1.23      www      2019:     $filename=~s/\/+/\//g;
1.607     raeburn  2020:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2021:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2022:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2023: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2024: 	return &repcopy_userfile($filename);
                   2025:     }
1.532     albertel 2026:     $filename=~s/[\n\r]//g;
1.8       www      2027:     my $transname="$filename.in.transfer";
1.828     www      2028: # FIXME: this should flock
1.607     raeburn  2029:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2030:     my $remoteurl=subscribe($filename);
1.64      www      2031:     if ($remoteurl =~ /^con_lost by/) {
                   2032: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2033:            return 'unavailable';
1.8       www      2034:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2035: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2036: 	   return 'not_found';
1.64      www      2037:     } elsif ($remoteurl =~ /^rejected by/) {
                   2038: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2039:            return 'forbidden';
1.20      www      2040:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2041:            return 'ok';
1.8       www      2042:     } else {
1.290     www      2043:         my $author=$filename;
                   2044:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2045:         my ($udom,$uname)=split(/\//,$author);
                   2046:         my $home=homeserver($uname,$udom);
                   2047:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2048:            my @parts=split(/\//,$filename);
                   2049:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2050:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2051:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2052: 	       return 'bad_request';
1.8       www      2053:            }
                   2054:            my $count;
                   2055:            for ($count=5;$count<$#parts;$count++) {
                   2056:                $path.="/$parts[$count]";
                   2057:                if ((-e $path)!=1) {
                   2058: 		   mkdir($path,0777);
                   2059:                }
                   2060:            }
                   2061:            my $ua=new LWP::UserAgent;
                   2062:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2063:            my $response=$ua->request($request,$transname);
                   2064:            if ($response->is_error()) {
                   2065: 	       unlink($transname);
                   2066:                my $message=$response->status_line;
1.672     albertel 2067:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2068:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2069:                return 'unavailable';
1.8       www      2070:            } else {
1.16      www      2071: 	       if ($remoteurl!~/\.meta$/) {
                   2072:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2073:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2074:                   if ($mresponse->is_error()) {
                   2075: 		      unlink($filename.'.meta');
                   2076:                       &logthis(
1.672     albertel 2077:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2078:                   }
                   2079: 	       }
1.8       www      2080:                rename($transname,$filename);
1.607     raeburn  2081:                return 'ok';
1.8       www      2082:            }
1.290     www      2083:        }
1.8       www      2084:     }
1.330     www      2085: }
                   2086: 
                   2087: # ------------------------------------------------ Get server side include body
                   2088: sub ssi_body {
1.381     albertel 2089:     my ($filelink,%form)=@_;
1.606     matthew  2090:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2091:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2092:     }
1.953     www      2093:     my $output='';
                   2094:     my $response;
1.980     raeburn  2095:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2096:        ($output,$response)=&externalssi($filelink);
1.953     www      2097:     } else {
1.1004    droeschl 2098:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2099:        $filelink .= 'inhibitmenu=yes';
1.953     www      2100:        ($output,$response)=&ssi($filelink,%form);
                   2101:     }
1.778     albertel 2102:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2103:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2104:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2105:     if (wantarray) {
                   2106:         return ($output, $response);
                   2107:     } else {
                   2108:         return $output;
                   2109:     }
1.8       www      2110: }
                   2111: 
1.15      www      2112: # --------------------------------------------------------- Server Side Include
                   2113: 
1.782     albertel 2114: sub absolute_url {
                   2115:     my ($host_name) = @_;
                   2116:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2117:     if ($host_name eq '') {
                   2118: 	$host_name = $ENV{'SERVER_NAME'};
                   2119:     }
                   2120:     return $protocol.$host_name;
                   2121: }
                   2122: 
1.942     foxr     2123: #
                   2124: #   Server side include.
                   2125: # Parameters:
                   2126: #  fn     Possibly encrypted resource name/id.
                   2127: #  form   Hash that describes how the rendering should be done
                   2128: #         and other things.
1.944     foxr     2129: # Returns:
1.950     raeburn  2130: #   Scalar context: The content of the response.
                   2131: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2132: #     
1.15      www      2133: sub ssi {
                   2134: 
1.944     foxr     2135:     my ($fn,%form)=@_;
1.15      www      2136:     my $ua=new LWP::UserAgent;
1.23      www      2137:     my $request;
1.711     albertel 2138: 
                   2139:     $form{'no_update_last_known'}=1;
1.895     albertel 2140:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2141:     if (%form) {
1.782     albertel 2142:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2143:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2144:     } else {
1.782     albertel 2145:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2146:     }
                   2147: 
1.15      www      2148:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2149:     my $response=$ua->request($request);
                   2150: 
1.944     foxr     2151:     if (wantarray) {
                   2152: 	return ($response->content, $response);
                   2153:     } else {
                   2154: 	return $response->content;
1.942     foxr     2155:     }
1.324     www      2156: }
                   2157: 
                   2158: sub externalssi {
                   2159:     my ($url)=@_;
                   2160:     my $ua=new LWP::UserAgent;
                   2161:     my $request=new HTTP::Request('GET',$url);
                   2162:     my $response=$ua->request($request);
1.954     raeburn  2163:     if (wantarray) {
                   2164:         return ($response->content, $response);
                   2165:     } else {
                   2166:         return $response->content;
                   2167:     }
1.15      www      2168: }
1.254     www      2169: 
1.492     albertel 2170: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2171: 
                   2172: sub allowuploaded {
                   2173:     my ($srcurl,$url)=@_;
                   2174:     $url=&clutter(&declutter($url));
                   2175:     my $dir=$url;
                   2176:     $dir=~s/\/[^\/]+$//;
                   2177:     my %httpref=();
                   2178:     my $httpurl=&hreflocation('',$url);
                   2179:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2180:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2181: }
1.477     raeburn  2182: 
1.478     albertel 2183: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2184: # input: action, courseID, current domain, intended
1.637     raeburn  2185: #        path to file, source of file, instruction to parse file for objects,
                   2186: #        ref to hash for embedded objects,
                   2187: #        ref to hash for codebase of java objects.
1.1095    raeburn  2188: #        reference to scalar to accommodate mime type determined
                   2189: #          from File::MMagic if $parser = parse.
1.637     raeburn  2190: #
1.485     raeburn  2191: # output: url to file (if action was uploaddoc), 
                   2192: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2193: #
1.478     albertel 2194: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2195: # course.
1.477     raeburn  2196: #
1.478     albertel 2197: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2198: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2199: #          course's home server.
1.477     raeburn  2200: #
1.478     albertel 2201: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2202: #          be copied from $source (current location) to 
                   2203: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2204: #         and will then be copied to
                   2205: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2206: #         course's home server.
1.485     raeburn  2207: #
1.481     raeburn  2208: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2209: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2210: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2211: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2212: #         in course's home server.
1.637     raeburn  2213: #
1.477     raeburn  2214: 
                   2215: sub process_coursefile {
1.1095    raeburn  2216:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2217:         $mimetype)=@_;
1.477     raeburn  2218:     my $fetchresult;
1.638     albertel 2219:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2220:     if ($action eq 'propagate') {
1.638     albertel 2221:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2222: 			     $home);
1.481     raeburn  2223:     } else {
1.477     raeburn  2224:         my $fpath = '';
                   2225:         my $fname = $file;
1.478     albertel 2226:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2227:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2228:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2229:         if ($action eq 'copy') {
                   2230:             if ($source eq '') {
                   2231:                 $fetchresult = 'no source file';
                   2232:                 return $fetchresult;
                   2233:             } else {
                   2234:                 my $destination = $filepath.'/'.$fname;
                   2235:                 rename($source,$destination);
                   2236:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2237:                                  $home);
1.481     raeburn  2238:             }
                   2239:         } elsif ($action eq 'uploaddoc') {
                   2240:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2241:             print $fh $env{'form.'.$source};
1.481     raeburn  2242:             close($fh);
1.637     raeburn  2243:             if ($parser eq 'parse') {
1.1024    raeburn  2244:                 my $mm = new File::MMagic;
1.1095    raeburn  2245:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2246:                 if ($type eq 'text/html') {
1.1024    raeburn  2247:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2248:                     unless ($parse_result eq 'ok') {
                   2249:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2250:                     }
1.637     raeburn  2251:                 }
1.1095    raeburn  2252:                 if (ref($mimetype)) {
                   2253:                     $$mimetype = $type;
                   2254:                 } 
1.637     raeburn  2255:             }
1.477     raeburn  2256:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2257:                                  $home);
1.481     raeburn  2258:             if ($fetchresult eq 'ok') {
                   2259:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2260:             } else {
                   2261:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2262:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2263:                 return '/adm/notfound.html';
                   2264:             }
1.477     raeburn  2265:         }
                   2266:     }
1.485     raeburn  2267:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2268:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2269:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2270:     }
                   2271:     return $fetchresult;
                   2272: }
                   2273: 
1.637     raeburn  2274: sub build_filepath {
                   2275:     my ($fpath) = @_;
                   2276:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2277:     unless ($fpath eq '') {
                   2278:         my @parts=split('/',$fpath);
                   2279:         foreach my $part (@parts) {
                   2280:             $filepath.= '/'.$part;
                   2281:             if ((-e $filepath)!=1) {
                   2282:                 mkdir($filepath,0777);
                   2283:             }
                   2284:         }
                   2285:     }
                   2286:     return $filepath;
                   2287: }
                   2288: 
                   2289: sub store_edited_file {
1.638     albertel 2290:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2291:     my $file = $primary_url;
                   2292:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2293:     my $fpath = '';
                   2294:     my $fname = $file;
                   2295:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2296:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2297:     my $filepath = &build_filepath($fpath);
                   2298:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2299:     print $fh $content;
                   2300:     close($fh);
1.638     albertel 2301:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2302:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2303: 			  $home);
1.637     raeburn  2304:     if ($$fetchresult eq 'ok') {
                   2305:         return '/uploaded/'.$fpath.'/'.$fname;
                   2306:     } else {
1.638     albertel 2307:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2308: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2309:         return '/adm/notfound.html';
                   2310:     }
                   2311: }
                   2312: 
1.531     albertel 2313: sub clean_filename {
1.831     albertel 2314:     my ($fname,$args)=@_;
1.315     www      2315: # Replace Windows backslashes by forward slashes
1.257     www      2316:     $fname=~s/\\/\//g;
1.831     albertel 2317:     if (!$args->{'keep_path'}) {
                   2318:         # Get rid of everything but the actual filename
                   2319: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2320:     }
1.315     www      2321: # Replace spaces by underscores
                   2322:     $fname=~s/\s+/\_/g;
                   2323: # Replace all other weird characters by nothing
1.831     albertel 2324:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2325: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2326: # numbers
                   2327:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2328:     return $fname;
                   2329: }
1.1051    raeburn  2330: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2331: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2332: # image with the same aspect ratio as the original, but with dimensions which do 
                   2333: # not exceed $resizewidth and $resizeheight.
                   2334:  
1.984     neumanie 2335: sub resizeImage {
1.1051    raeburn  2336:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2337:     my $ima = Image::Magick->new;
                   2338:     my $resized;
                   2339:     if (-e $img_path) {
                   2340:         $ima->Read($img_path);
                   2341:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2342:             my $width = $ima->Get('width');
                   2343:             my $height = $ima->Get('height');
                   2344:             if ($width > $resizewidth) {
                   2345: 	        my $factor = $width/$resizewidth;
                   2346:                 my $newheight = $height/$factor;
                   2347:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2348:                 $resized = 1;
                   2349:             }
                   2350:         }
                   2351:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2352:             my $width = $ima->Get('width');
                   2353:             my $height = $ima->Get('height');
                   2354:             if ($height > $resizeheight) {
                   2355:                 my $factor = $height/$resizeheight;
                   2356:                 my $newwidth = $width/$factor;
                   2357:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2358:                 $resized = 1;
                   2359:             }
                   2360:         }
                   2361:         if ($resized) {
                   2362:             $ima->Write($img_path);
                   2363:         }
                   2364:     }
                   2365:     return;
1.977     amueller 2366: }
                   2367: 
1.608     albertel 2368: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2369: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2370: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2371: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2372: #                                    canceloverwrite, or ''. 
                   2373: #                   if 'coursedoc': upload to the current course
                   2374: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2375: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2376: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2377: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2378: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2379: #        $allfiles - reference to hash for embedded objects
                   2380: #        $codebase - reference to hash for codebase of java objects
                   2381: #        $desuname - username for permanent storage of uploaded file
                   2382: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2383: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2384: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2385: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2386: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2387: #        $mimetype - reference to scalar to accommodate mime type determined
                   2388: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2389: # 
1.686     albertel 2390: # output: url of file in userspace, or error: <message> 
                   2391: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2392: 
1.531     albertel 2393: sub userfileupload {
1.1090    raeburn  2394:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2395:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2396:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2397:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2398:     $fname=&clean_filename($fname);
1.1090    raeburn  2399:     # See if there is anything left
1.257     www      2400:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2401:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2402:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2403:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2404:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2405:         my $now = time;
1.1090    raeburn  2406:         my $filepath;
1.1095    raeburn  2407:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2408:              $filepath = 'tmp/helprequests/'.$now;
                   2409:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2410:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2411:                          '_'.$env{'user.domain'}.'/pending';
                   2412:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2413:             my ($docuname,$docudom);
                   2414:             if ($destudom) {
                   2415:                 $docudom = $destudom;
                   2416:             } else {
                   2417:                 $docudom = $env{'user.domain'};
                   2418:             }
                   2419:             if ($destuname) {
                   2420:                 $docuname = $destuname;
                   2421:             } else {
                   2422:                 $docuname = $env{'user.name'};
                   2423:             }
                   2424:             if (exists($env{'form.group'})) {
                   2425:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2426:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2427:             }
                   2428:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2429:             if ($context eq 'canceloverwrite') {
                   2430:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2431:                 if (-e  $tempfile) {
                   2432:                     my @info = stat($tempfile);
                   2433:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2434:                         unlink($tempfile);
                   2435:                     }
                   2436:                 }
                   2437:                 return;
1.523     raeburn  2438:             }
                   2439:         }
1.1090    raeburn  2440:         # Create the directory if not present
1.741     raeburn  2441:         my @parts=split(/\//,$filepath);
                   2442:         my $fullpath = $perlvar{'lonDaemons'};
                   2443:         for (my $i=0;$i<@parts;$i++) {
                   2444:             $fullpath .= '/'.$parts[$i];
                   2445:             if ((-e $fullpath)!=1) {
                   2446:                 mkdir($fullpath,0777);
                   2447:             }
                   2448:         }
                   2449:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2450:         print $fh $env{'form.'.$formname};
                   2451:         close($fh);
1.1090    raeburn  2452:         if ($context eq 'existingfile') {
                   2453:             my @info = stat($fullpath.'/'.$fname);
                   2454:             return ($fullpath.'/'.$fname,$info[9]);
                   2455:         } else {
                   2456:             return $fullpath.'/'.$fname;
                   2457:         }
1.523     raeburn  2458:     }
1.995     raeburn  2459:     if ($subdir eq 'scantron') {
                   2460:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2461:     } else {
1.995     raeburn  2462:         $fname="$subdir/$fname";
                   2463:     }
1.1090    raeburn  2464:     if ($context eq 'coursedoc') {
1.638     albertel 2465: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2466: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2467:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2468:             return &finishuserfileupload($docuname,$docudom,
                   2469: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2470: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2471:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2472:         } else {
1.620     albertel 2473:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2474:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2475: 				       $fname,$formname,$parser,
1.1095    raeburn  2476: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2477:         }
1.719     banghart 2478:     } elsif (defined($destuname)) {
                   2479:         my $docuname=$destuname;
                   2480:         my $docudom=$destudom;
1.860     raeburn  2481: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2482: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2483:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2484:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2485:     } else {
1.638     albertel 2486:         my $docuname=$env{'user.name'};
                   2487:         my $docudom=$env{'user.domain'};
1.714     raeburn  2488:         if (exists($env{'form.group'})) {
                   2489:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2490:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2491:         }
1.860     raeburn  2492: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2493: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2494:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2495:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2496:     }
1.271     www      2497: }
                   2498: 
                   2499: sub finishuserfileupload {
1.860     raeburn  2500:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2501:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2502:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2503:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2504:   
1.860     raeburn  2505:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2506:     $file=$fname;
                   2507:     if ($fname=~m|/|) {
                   2508:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2509: 	$path.=$fnamepath.'/';
                   2510:     }
1.259     www      2511:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2512:     my $count;
                   2513:     for ($count=4;$count<=$#parts;$count++) {
                   2514:         $filepath.="/$parts[$count]";
                   2515:         if ((-e $filepath)!=1) {
                   2516: 	    mkdir($filepath,0777);
                   2517:         }
                   2518:     }
1.984     neumanie 2519: 
1.258     www      2520: # Save the file
                   2521:     {
1.701     albertel 2522: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2523: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2524: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2525: 	    return '/adm/notfound.html';
                   2526: 	}
1.1090    raeburn  2527:         if ($context eq 'overwrite') {
                   2528:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2529:             my $target = $filepath.'/'.$file;
                   2530:             if (-e $source) {
                   2531:                 my @info = stat($source);
                   2532:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2533:                     unless (&File::Copy::move($source,$target)) {
                   2534:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2535:                         return "Moving from $source failed";
                   2536:                     }
                   2537:                 } else {
                   2538:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2539:                 }
                   2540:             } else {
                   2541:                 return "Temporary file: $source missing";
                   2542:             }
                   2543:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2544: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2545: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2546: 	    return '/adm/notfound.html';
                   2547: 	}
1.570     albertel 2548: 	close(FH);
1.1051    raeburn  2549:         if ($resizewidth && $resizeheight) {
                   2550:             my $mm = new File::MMagic;
                   2551:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2552:             if ($mime_type =~ m{^image/}) {
                   2553: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2554:             }  
1.977     amueller 2555: 	}
1.258     www      2556:     }
1.637     raeburn  2557:     if ($parser eq 'parse') {
1.1024    raeburn  2558:         my $mm = new File::MMagic;
1.1095    raeburn  2559:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2560:         if ($type eq 'text/html') {
1.1024    raeburn  2561:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2562:                                                        $allfiles,$codebase);
                   2563:             unless ($parse_result eq 'ok') {
                   2564:                 &logthis('Failed to parse '.$filepath.$file.
                   2565: 	   	         ' for embedded media: '.$parse_result); 
                   2566:             }
1.637     raeburn  2567:         }
1.1095    raeburn  2568:         if (ref($mimetype)) {
                   2569:             $$mimetype = $type;
                   2570:         }
1.637     raeburn  2571:     }
1.860     raeburn  2572:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2573:         my $input = $filepath.'/'.$file;
                   2574:         my $output = $filepath.'/'.'tn-'.$file;
                   2575:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2576:         system("convert -sample $thumbsize $input $output");
                   2577:         if (-e $filepath.'/'.'tn-'.$file) {
                   2578:             $fetchthumb  = 1; 
                   2579:         }
                   2580:     }
1.858     raeburn  2581:  
1.259     www      2582: # Notify homeserver to grep it
                   2583: #
1.984     neumanie 2584:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2585:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2586:     if ($fetchresult eq 'ok') {
1.860     raeburn  2587:         if ($fetchthumb) {
                   2588:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2589:             if ($thumbresult ne 'ok') {
                   2590:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2591:                          $docuhome.': '.$thumbresult);
                   2592:             }
                   2593:         }
1.259     www      2594: #
1.258     www      2595: # Return the URL to it
1.494     albertel 2596:         return '/uploaded/'.$path.$file;
1.263     www      2597:     } else {
1.494     albertel 2598:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2599: 		 ': '.$fetchresult);
1.263     www      2600:         return '/adm/notfound.html';
1.858     raeburn  2601:     }
1.493     albertel 2602: }
                   2603: 
1.637     raeburn  2604: sub extract_embedded_items {
1.961     raeburn  2605:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2606:     my @state = ();
                   2607:     my %javafiles = (
                   2608:                       codebase => '',
                   2609:                       code => '',
                   2610:                       archive => ''
                   2611:                     );
                   2612:     my %mediafiles = (
                   2613:                       src => '',
                   2614:                       movie => '',
                   2615:                      );
1.648     raeburn  2616:     my $p;
                   2617:     if ($content) {
                   2618:         $p = HTML::LCParser->new($content);
                   2619:     } else {
1.961     raeburn  2620:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2621:     }
1.641     albertel 2622:     while (my $t=$p->get_token()) {
1.640     albertel 2623: 	if ($t->[0] eq 'S') {
                   2624: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2625: 	    push(@state, $tagname);
1.648     raeburn  2626:             if (lc($tagname) eq 'allow') {
                   2627:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2628:             }
1.640     albertel 2629: 	    if (lc($tagname) eq 'img') {
                   2630: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2631: 	    }
1.886     albertel 2632: 	    if (lc($tagname) eq 'a') {
                   2633: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2634: 	    }
1.645     raeburn  2635:             if (lc($tagname) eq 'script') {
                   2636:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2637:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2638:                 } else {
                   2639:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2640:                 }
                   2641:             }
                   2642:             if (lc($tagname) eq 'link') {
                   2643:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2644:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2645:                 }
                   2646:             }
1.640     albertel 2647: 	    if (lc($tagname) eq 'object' ||
                   2648: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2649: 		foreach my $item (keys(%javafiles)) {
                   2650: 		    $javafiles{$item} = '';
                   2651: 		}
                   2652: 	    }
                   2653: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2654: 		my $name = lc($attr->{'name'});
                   2655: 		foreach my $item (keys(%javafiles)) {
                   2656: 		    if ($name eq $item) {
                   2657: 			$javafiles{$item} = $attr->{'value'};
                   2658: 			last;
                   2659: 		    }
                   2660: 		}
                   2661: 		foreach my $item (keys(%mediafiles)) {
                   2662: 		    if ($name eq $item) {
                   2663: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2664: 			last;
                   2665: 		    }
                   2666: 		}
                   2667: 	    }
                   2668: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2669: 		foreach my $item (keys(%javafiles)) {
                   2670: 		    if ($attr->{$item}) {
                   2671: 			$javafiles{$item} = $attr->{$item};
                   2672: 			last;
                   2673: 		    }
                   2674: 		}
                   2675: 		foreach my $item (keys(%mediafiles)) {
                   2676: 		    if ($attr->{$item}) {
                   2677: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2678: 			last;
                   2679: 		    }
                   2680: 		}
                   2681: 	    }
                   2682: 	} elsif ($t->[0] eq 'E') {
                   2683: 	    my ($tagname) = ($t->[1]);
                   2684: 	    if ($javafiles{'codebase'} ne '') {
                   2685: 		$javafiles{'codebase'} .= '/';
                   2686: 	    }  
                   2687: 	    if (lc($tagname) eq 'applet' ||
                   2688: 		lc($tagname) eq 'object' ||
                   2689: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2690: 		) {
                   2691: 		foreach my $item (keys(%javafiles)) {
                   2692: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2693: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2694: 			&add_filetype($allfiles,$file,$item);
                   2695: 		    }
                   2696: 		}
                   2697: 	    } 
                   2698: 	    pop @state;
                   2699: 	}
                   2700:     }
1.637     raeburn  2701:     return 'ok';
                   2702: }
                   2703: 
1.639     albertel 2704: sub add_filetype {
                   2705:     my ($allfiles,$file,$type)=@_;
                   2706:     if (exists($allfiles->{$file})) {
                   2707: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2708: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2709: 	}
                   2710:     } else {
                   2711: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2712:     }
                   2713: }
                   2714: 
1.493     albertel 2715: sub removeuploadedurl {
1.984     neumanie 2716:     my ($url)=@_;	
                   2717:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2718:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2719: }
                   2720: 
                   2721: sub removeuserfile {
                   2722:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2723:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2724:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2725:     if ($result eq 'ok') {	
1.798     raeburn  2726:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2727:             my $metafile = $fname.'.meta';
                   2728:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2729: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2730:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2731:             my $sqlresult = 
1.823     albertel 2732:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2733:                                         'portfolio_metadata',$group,
                   2734:                                         'delete');
1.798     raeburn  2735:         }
                   2736:     }
                   2737:     return $result;
1.257     www      2738: }
1.15      www      2739: 
1.530     albertel 2740: sub mkdiruserfile {
                   2741:     my ($docuname,$docudom,$dir)=@_;
                   2742:     my $home=&homeserver($docuname,$docudom);
                   2743:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2744: }
                   2745: 
1.531     albertel 2746: sub renameuserfile {
                   2747:     my ($docuname,$docudom,$old,$new)=@_;
                   2748:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2749:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2750:                         &escape("$old").':'.&escape("$new"),$home);
                   2751:     if ($result eq 'ok') {
                   2752:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2753:             my $oldmeta = $old.'.meta';
                   2754:             my $newmeta = $new.'.meta';
                   2755:             my $metaresult = 
                   2756:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2757: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2758:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2759:             my $sqlresult = 
1.823     albertel 2760:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2761:                                         'portfolio_metadata',$group,
                   2762:                                         'delete');
1.798     raeburn  2763:         }
                   2764:     }
                   2765:     return $result;
1.531     albertel 2766: }
                   2767: 
1.14      www      2768: # ------------------------------------------------------------------------- Log
                   2769: 
                   2770: sub log {
                   2771:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2772:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2773: }
                   2774: 
                   2775: # ------------------------------------------------------------------ Course Log
1.352     www      2776: #
                   2777: # This routine flushes several buffers of non-mission-critical nature
                   2778: #
1.157     www      2779: 
                   2780: sub flushcourselogs {
1.352     www      2781:     &logthis('Flushing log buffers');
                   2782: #
                   2783: # course logs
                   2784: # This is a log of all transactions in a course, which can be used
                   2785: # for data mining purposes
                   2786: #
                   2787: # It also collects the courseid database, which lists last transaction
                   2788: # times and course titles for all courseids
                   2789: #
                   2790:     my %courseidbuffer=();
1.921     raeburn  2791:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2792:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2793: 		          &escape($courselogs{$crsid}),
                   2794: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2795: 	    delete $courselogs{$crsid};
                   2796:         } else {
                   2797:             &logthis('Failed to flush log buffer for '.$crsid);
                   2798:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2799:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2800:                         " exceeded maximum size, deleting.</font>");
                   2801:                delete $courselogs{$crsid};
                   2802:             }
1.352     www      2803:         }
1.920     raeburn  2804:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2805:             'description' => $coursedescrbuf{$crsid},
                   2806:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2807:             'type'        => $coursetypebuf{$crsid},
                   2808:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2809:         };
1.191     harris41 2810:     }
1.352     www      2811: #
                   2812: # Write course id database (reverse lookup) to homeserver of courses 
                   2813: # Is used in pickcourse
                   2814: #
1.840     albertel 2815:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2816:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2817:                                     $courseidbuffer{$crs_home},
                   2818:                                     $crs_home,'timeonly');
1.352     www      2819:     }
                   2820: #
                   2821: # File accesses
                   2822: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2823: #
1.449     matthew  2824:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2825:         if ($entry =~ /___count$/) {
                   2826:             my ($dom,$name);
1.807     albertel 2827:             ($dom,$name,undef)=
1.811     albertel 2828: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2829:             if (! defined($dom) || $dom eq '' || 
                   2830:                 ! defined($name) || $name eq '') {
1.620     albertel 2831:                 my $cid = $env{'request.course.id'};
                   2832:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2833:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2834:             }
1.450     matthew  2835:             my $value = $accesshash{$entry};
                   2836:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2837:             my %temphash=($url => $value);
1.449     matthew  2838:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2839:             if ($result eq 'ok') {
                   2840:                 delete $accesshash{$entry};
                   2841:             } elsif ($result eq 'unknown_cmd') {
                   2842:                 # Target server has old code running on it.
1.450     matthew  2843:                 my %temphash=($entry => $value);
1.449     matthew  2844:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2845:                     delete $accesshash{$entry};
                   2846:                 }
                   2847:             }
                   2848:         } else {
1.811     albertel 2849:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2850:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2851:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2852:                 delete $accesshash{$entry};
                   2853:             }
1.185     www      2854:         }
1.191     harris41 2855:     }
1.352     www      2856: #
                   2857: # Roles
                   2858: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2859: #
1.800     albertel 2860:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2861:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2862: 	    split(/\:/,$entry);
                   2863:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2864:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2865:                 $rudom,$runame) eq 'ok') {
                   2866: 	    delete $userrolehash{$entry};
                   2867:         }
                   2868:     }
1.662     raeburn  2869: #
                   2870: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2871: #
                   2872:     my %domrolebuffer = ();
1.1000    raeburn  2873:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2874:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2875:         if ($domrolebuffer{$rudom}) {
                   2876:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2877:                       '='.&escape($domainrolehash{$entry});
                   2878:         } else {
                   2879:             $domrolebuffer{$rudom}.=&escape($entry).
                   2880:                       '='.&escape($domainrolehash{$entry});
                   2881:         }
                   2882:         delete $domainrolehash{$entry};
                   2883:     }
                   2884:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2885: 	my %servers = &get_servers($dom,'library');
                   2886: 	foreach my $tryserver (keys(%servers)) {
                   2887: 	    unless (&reply('domroleput:'.$dom.':'.
                   2888: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2889: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2890: 	    }
1.662     raeburn  2891:         }
                   2892:     }
1.186     www      2893:     $dumpcount++;
1.157     www      2894: }
                   2895: 
                   2896: sub courselog {
                   2897:     my $what=shift;
1.158     www      2898:     $what=time.':'.$what;
1.620     albertel 2899:     unless ($env{'request.course.id'}) { return ''; }
                   2900:     $coursedombuf{$env{'request.course.id'}}=
                   2901:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2902:     $coursenumbuf{$env{'request.course.id'}}=
                   2903:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2904:     $coursehombuf{$env{'request.course.id'}}=
                   2905:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2906:     $coursedescrbuf{$env{'request.course.id'}}=
                   2907:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2908:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2909:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2910:     $courseownerbuf{$env{'request.course.id'}}=
                   2911:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2912:     $coursetypebuf{$env{'request.course.id'}}=
                   2913:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2914:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2915: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2916:     } else {
1.620     albertel 2917: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2918:     }
1.620     albertel 2919:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2920: 	&flushcourselogs();
                   2921:     }
1.158     www      2922: }
                   2923: 
                   2924: sub courseacclog {
                   2925:     my $fnsymb=shift;
1.620     albertel 2926:     unless ($env{'request.course.id'}) { return ''; }
                   2927:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2928:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2929:         $what.=':POST';
1.583     matthew  2930:         # FIXME: Probably ought to escape things....
1.800     albertel 2931: 	foreach my $key (keys(%env)) {
                   2932:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2933:                 my $formitem = $1;
                   2934:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2935:                     $what.=':'.$formitem.'='.$env{$key};
                   2936:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2937:                     $what.=':'.$formitem.'='.$env{$key};
                   2938:                 }
1.158     www      2939:             }
1.191     harris41 2940:         }
1.583     matthew  2941:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2942:         # FIXME: We should not be depending on a form parameter that someone
                   2943:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2944:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2945:             $what.= ':POST';
                   2946:             # FIXME: Probably ought to escape things....
                   2947:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2948:                                  'crsdiscuss') {
1.620     albertel 2949:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2950:             }
                   2951:         }
1.158     www      2952:     }
                   2953:     &courselog($what);
1.149     www      2954: }
                   2955: 
1.185     www      2956: sub countacc {
                   2957:     my $url=&declutter(shift);
1.458     matthew  2958:     return if (! defined($url) || $url eq '');
1.620     albertel 2959:     unless ($env{'request.course.id'}) { return ''; }
                   2960:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2961:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2962:     $accesshash{$key}++;
1.185     www      2963: }
1.349     www      2964: 
1.361     www      2965: sub linklog {
                   2966:     my ($from,$to)=@_;
                   2967:     $from=&declutter($from);
                   2968:     $to=&declutter($to);
                   2969:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2970:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2971: }
                   2972:   
1.349     www      2973: sub userrolelog {
                   2974:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2975:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2976:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2977:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2978:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2979:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2980:        $userrolehash
                   2981:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2982:                     =$tend.':'.$tstart;
1.662     raeburn  2983:     }
1.898     albertel 2984:     if (($env{'request.role'} =~ /dc\./) &&
                   2985: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2986: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2987: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2988:          ($trole=~/^co/))) {
1.898     albertel 2989:        $userrolehash
                   2990:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2991:                     =$tend.':'.$tstart;
                   2992:     }
1.662     raeburn  2993:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2994:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2995:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2996:         ($trole=~/^sc/)) {
                   2997:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2998:        $domainrolehash
                   2999:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3000:                     = $tend.':'.$tstart;
                   3001:     }
1.351     www      3002: }
                   3003: 
1.957     raeburn  3004: sub courserolelog {
                   3005:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3006:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3007:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3008:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3009:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3010:         ($trole eq 'co')) {
1.957     raeburn  3011:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3012:             my $cdom = $1;
                   3013:             my $cnum = $2;
                   3014:             my $sec = $3;
                   3015:             my $namespace = 'rolelog';
                   3016:             my %storehash = (
                   3017:                                role    => $trole,
                   3018:                                start   => $tstart,
                   3019:                                end     => $tend,
                   3020:                                selfenroll => $selfenroll,
                   3021:                                context    => $context,
                   3022:                             );
                   3023:             if ($trole eq 'gr') {
                   3024:                 $namespace = 'groupslog';
                   3025:                 $storehash{'group'} = $sec;
                   3026:             } else {
                   3027:                 $storehash{'section'} = $sec;
                   3028:             }
                   3029:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3030:             if (($trole ne 'st') || ($sec ne '')) {
                   3031:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3032:             }
1.957     raeburn  3033:         }
                   3034:     }
                   3035:     return;
                   3036: }
                   3037: 
1.351     www      3038: sub get_course_adv_roles {
1.948     raeburn  3039:     my ($cid,$codes) = @_;
1.620     albertel 3040:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3041:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3042:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3043:     my %nothide=();
1.800     albertel 3044:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3045:         if ($user !~ /:/) {
                   3046: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3047:         } else {
                   3048:             $nothide{$user}=1;
                   3049:         }
1.470     www      3050:     }
1.351     www      3051:     my %returnhash=();
                   3052:     my %dumphash=
                   3053:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3054:     my $now=time;
1.997     raeburn  3055:     my %privileged;
1.1000    raeburn  3056:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3057: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3058:         if (($tstart) && ($tstart<0)) { next; }
                   3059:         if (($tend) && ($tend<$now)) { next; }
                   3060:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3061:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3062: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3063:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3064:             my %dompersonnel =
1.998     raeburn  3065:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3066:             $privileged{$domain} = {};
                   3067:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3068:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3069:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3070:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3071:                         $privileged{$udom}{$uname} = 1;
                   3072:                     }
                   3073:                 }
                   3074:             }
                   3075:         }
                   3076:         if ((exists($privileged{$domain}{$username})) && 
                   3077:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3078: 	if ($role eq 'cr') { next; }
1.948     raeburn  3079:         if ($codes) {
                   3080:             if ($section) { $role .= ':'.$section; }
                   3081:             if ($returnhash{$role}) {
                   3082:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3083:             } else {
                   3084:                 $returnhash{$role}=$username.':'.$domain;
                   3085:             }
1.351     www      3086:         } else {
1.988     raeburn  3087:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3088:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3089:             if ($returnhash{$key}) {
                   3090: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3091:             } else {
                   3092:                 $returnhash{$key}=$username.':'.$domain;
                   3093:             }
1.351     www      3094:         }
1.948     raeburn  3095:     }
1.400     www      3096:     return %returnhash;
                   3097: }
                   3098: 
                   3099: sub get_my_roles {
1.937     raeburn  3100:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3101:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3102:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3103:     my (%dumphash,%nothide);
1.1086    raeburn  3104:     if ($context eq 'userroles') {
                   3105:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3106:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3107:     } else {
                   3108:         %dumphash=
1.400     www      3109:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3110:         if ($hidepriv) {
                   3111:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3112:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3113:                 if ($user !~ /:/) {
                   3114:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3115:                 } else {
                   3116:                     $nothide{$user} = 1;
                   3117:                 }
                   3118:             }
                   3119:         }
1.858     raeburn  3120:     }
1.400     www      3121:     my %returnhash=();
                   3122:     my $now=time;
1.999     raeburn  3123:     my %privileged;
1.800     albertel 3124:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3125:         my ($role,$tend,$tstart);
                   3126:         if ($context eq 'userroles') {
                   3127: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3128:         } else {
                   3129:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3130:         }
1.400     www      3131:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3132:         my $status = 'active';
1.939     raeburn  3133:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3134:             $status = 'previous';
                   3135:         } 
                   3136:         if (($tstart) && ($now<$tstart)) {
                   3137:             $status = 'future';
                   3138:         }
                   3139:         if (ref($types) eq 'ARRAY') {
                   3140:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3141:                 next;
                   3142:             } 
                   3143:         } else {
                   3144:             if ($status ne 'active') {
                   3145:                 next;
                   3146:             }
                   3147:         }
1.867     raeburn  3148:         my ($rolecode,$username,$domain,$section,$area);
                   3149:         if ($context eq 'userroles') {
                   3150:             ($area,$rolecode) = split(/_/,$entry);
                   3151:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3152:         } else {
                   3153:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3154:         }
1.832     raeburn  3155:         if (ref($roledoms) eq 'ARRAY') {
                   3156:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3157:                 next;
                   3158:             }
                   3159:         }
                   3160:         if (ref($roles) eq 'ARRAY') {
                   3161:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3162:                 if ($role =~ /^cr\//) {
                   3163:                     if (!grep(/^cr$/,@{$roles})) {
                   3164:                         next;
                   3165:                     }
1.1104    raeburn  3166:                 } elsif ($role =~ /^gr\//) {
                   3167:                     if (!grep(/^gr$/,@{$roles})) {
                   3168:                         next;
                   3169:                     }
1.922     raeburn  3170:                 } else {
                   3171:                     next;
                   3172:                 }
1.832     raeburn  3173:             }
1.867     raeburn  3174:         }
1.937     raeburn  3175:         if ($hidepriv) {
1.999     raeburn  3176:             if ($context eq 'userroles') {
                   3177:                 if ((&privileged($username,$domain)) &&
                   3178:                     (!$nothide{$username.':'.$domain})) {
                   3179:                     next;
                   3180:                 }
                   3181:             } else {
                   3182:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3183:                     my %dompersonnel =
                   3184:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3185:                     $privileged{$domain} = {};
                   3186:                     if (keys(%dompersonnel)) {
                   3187:                         foreach my $server (keys(%dompersonnel)) {
                   3188:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3189:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3190:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3191:                                     $privileged{$udom}{$uname} = $trole;
                   3192:                                 }
                   3193:                             }
                   3194:                         }
                   3195:                     }
                   3196:                 }
                   3197:                 if (exists($privileged{$domain}{$username})) {
                   3198:                     if (!$nothide{$username.':'.$domain}) {
                   3199:                         next;
                   3200:                     }
                   3201:                 }
1.937     raeburn  3202:             }
                   3203:         }
1.933     raeburn  3204:         if ($withsec) {
                   3205:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3206:                 $tstart.':'.$tend;
                   3207:         } else {
                   3208:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3209:         }
1.832     raeburn  3210:     }
1.373     www      3211:     return %returnhash;
1.399     www      3212: }
                   3213: 
                   3214: # ----------------------------------------------------- Frontpage Announcements
                   3215: #
                   3216: #
                   3217: 
                   3218: sub postannounce {
                   3219:     my ($server,$text)=@_;
1.844     albertel 3220:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3221:     unless ($text=~/\w/) { $text=''; }
                   3222:     return &reply('setannounce:'.&escape($text),$server);
                   3223: }
                   3224: 
                   3225: sub getannounce {
1.448     albertel 3226: 
                   3227:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3228: 	my $announcement='';
1.800     albertel 3229: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3230: 	close($fh);
1.399     www      3231: 	if ($announcement=~/\w/) { 
                   3232: 	    return 
                   3233:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3234:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3235: 	} else {
                   3236: 	    return '';
                   3237: 	}
                   3238:     } else {
                   3239: 	return '';
                   3240:     }
1.351     www      3241: }
1.353     www      3242: 
                   3243: # ---------------------------------------------------------- Course ID routines
                   3244: # Deal with domain's nohist_courseid.db files
                   3245: #
                   3246: 
                   3247: sub courseidput {
1.921     raeburn  3248:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3249:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3250:     my $outcome;
                   3251:     if ($caller eq 'timeonly') {
                   3252:         my $cids = '';
                   3253:         foreach my $item (keys(%$storehash)) {
                   3254:             $cids.=&escape($item).'&';
                   3255:         }
                   3256:         $cids=~s/\&$//;
                   3257:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3258:                           $coursehome);       
                   3259:     } else {
                   3260:         my $items = '';
                   3261:         foreach my $item (keys(%$storehash)) {
                   3262:             $items.= &escape($item).'='.
                   3263:                      &freeze_escape($$storehash{$item}).'&';
                   3264:         }
                   3265:         $items=~s/\&$//;
                   3266:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3267:                           $coursehome);
1.918     raeburn  3268:     }
                   3269:     if ($outcome eq 'unknown_cmd') {
                   3270:         my $what;
                   3271:         foreach my $cid (keys(%$storehash)) {
                   3272:             $what .= &escape($cid).'=';
1.921     raeburn  3273:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3274:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3275:             }
                   3276:             $what =~ s/\:$/&/;
                   3277:         }
                   3278:         $what =~ s/\&$//;  
                   3279:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3280:     } else {
                   3281:         return $outcome;
                   3282:     }
1.353     www      3283: }
                   3284: 
                   3285: sub courseiddump {
1.921     raeburn  3286:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3287:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3288:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3289:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3290:     my $as_hash = 1;
                   3291:     my %returnhash;
                   3292:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3293:     my %libserv = &all_library();
                   3294:     foreach my $tryserver (keys(%libserv)) {
                   3295:         if ( (  $hostidflag == 1 
                   3296: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3297: 	     || (!defined($hostidflag)) ) {
                   3298: 
1.918     raeburn  3299: 	    if (($domfilter eq '') ||
                   3300: 		(&host_domain($tryserver) eq $domfilter)) {
                   3301:                 my $rep = 
                   3302:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3303:                          $sincefilter.':'.&escape($descfilter).':'.
                   3304:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3305:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3306:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3307:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3308:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3309:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3310:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3311:                          &escape($creationcontext).':'.$domcloner,
                   3312:                          $tryserver);
1.918     raeburn  3313:                 my @pairs=split(/\&/,$rep);
                   3314:                 foreach my $item (@pairs) {
                   3315:                     my ($key,$value)=split(/\=/,$item,2);
                   3316:                     $key = &unescape($key);
                   3317:                     next if ($key =~ /^error: 2 /);
                   3318:                     my $result = &thaw_unescape($value);
                   3319:                     if (ref($result) eq 'HASH') {
                   3320:                         $returnhash{$key}=$result;
                   3321:                     } else {
1.921     raeburn  3322:                         my @responses = split(/:/,$value);
                   3323:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3324:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3325:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3326:                         }
1.1008    raeburn  3327:                     }
1.353     www      3328:                 }
                   3329:             }
                   3330:         }
                   3331:     }
                   3332:     return %returnhash;
                   3333: }
                   3334: 
1.1055    raeburn  3335: sub courselastaccess {
                   3336:     my ($cdom,$cnum,$hostidref) = @_;
                   3337:     my %returnhash;
                   3338:     if ($cdom && $cnum) {
                   3339:         my $chome = &homeserver($cnum,$cdom);
                   3340:         if ($chome ne 'no_host') {
                   3341:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3342:             &extract_lastaccess(\%returnhash,$rep);
                   3343:         }
                   3344:     } else {
                   3345:         if (!$cdom) { $cdom=''; }
                   3346:         my %libserv = &all_library();
                   3347:         foreach my $tryserver (keys(%libserv)) {
                   3348:             if (ref($hostidref) eq 'ARRAY') {
                   3349:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3350:             } 
                   3351:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3352:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3353:                 &extract_lastaccess(\%returnhash,$rep);
                   3354:             }
                   3355:         }
                   3356:     }
                   3357:     return %returnhash;
                   3358: }
                   3359: 
                   3360: sub extract_lastaccess {
                   3361:     my ($returnhash,$rep) = @_;
                   3362:     if (ref($returnhash) eq 'HASH') {
                   3363:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3364:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3365:                  $rep eq '') {
                   3366:             my @pairs=split(/\&/,$rep);
                   3367:             foreach my $item (@pairs) {
                   3368:                 my ($key,$value)=split(/\=/,$item,2);
                   3369:                 $key = &unescape($key);
                   3370:                 next if ($key =~ /^error: 2 /);
                   3371:                 $returnhash->{$key} = &thaw_unescape($value);
                   3372:             }
                   3373:         }
                   3374:     }
                   3375:     return;
                   3376: }
                   3377: 
1.658     raeburn  3378: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3379: 
                   3380: sub dcmailput {
1.685     raeburn  3381:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3382:     my $status = &Apache::lonnet::critical(
1.740     www      3383:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3384:        &escape($message),$server);
1.662     raeburn  3385:     return $status;
                   3386: }
                   3387: 
1.658     raeburn  3388: sub dcmaildump {
                   3389:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3390:     my %returnhash=();
1.846     albertel 3391: 
                   3392:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3393:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3394:                                                          &escape($enddate).':';
                   3395: 	my @esc_senders=map { &escape($_)} @$senders;
                   3396: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3397: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3398:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3399:             if (($key) && ($value)) {
                   3400:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3401:             }
                   3402:         }
                   3403:     }
                   3404:     return %returnhash;
                   3405: }
1.662     raeburn  3406: # ---------------------------------------------------------- Domain roles
                   3407: 
                   3408: sub get_domain_roles {
                   3409:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3410:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3411:         $startdate = '.';
                   3412:     }
1.1018    raeburn  3413:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3414:         $enddate = '.';
                   3415:     }
1.922     raeburn  3416:     my $rolelist;
                   3417:     if (ref($roles) eq 'ARRAY') {
                   3418:         $rolelist = join(':',@{$roles});
                   3419:     }
1.662     raeburn  3420:     my %personnel = ();
1.841     albertel 3421: 
                   3422:     my %servers = &get_servers($dom,'library');
                   3423:     foreach my $tryserver (keys(%servers)) {
                   3424: 	%{$personnel{$tryserver}}=();
                   3425: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3426: 					    &escape($startdate).':'.
                   3427: 					    &escape($enddate).':'.
                   3428: 					    &escape($rolelist), $tryserver))) {
                   3429: 	    my ($key,$value) = split(/\=/,$line,2);
                   3430: 	    if (($key) && ($value)) {
                   3431: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3432: 	    }
                   3433: 	}
1.662     raeburn  3434:     }
                   3435:     return %personnel;
                   3436: }
1.658     raeburn  3437: 
1.1057    www      3438: # ----------------------------------------------------------- Interval timing 
1.149     www      3439: 
1.504     albertel 3440: sub get_first_access {
                   3441:     my ($type,$argsymb)=@_;
1.790     albertel 3442:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3443:     if ($argsymb) { $symb=$argsymb; }
                   3444:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3445:     if ($type eq 'course') {
                   3446: 	$res='course';
                   3447:     } elsif ($type eq 'map') {
1.588     albertel 3448: 	$res=&symbread($map);
                   3449:     } else {
                   3450: 	$res=$symb;
                   3451:     }
                   3452:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3453:     return $times{"$courseid\0$res"};
1.504     albertel 3454: }
                   3455: 
                   3456: sub set_first_access {
                   3457:     my ($type)=@_;
1.790     albertel 3458:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3459:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3460:     if ($type eq 'course') {
                   3461: 	$res='course';
                   3462:     } elsif ($type eq 'map') {
1.588     albertel 3463: 	$res=&symbread($map);
                   3464:     } else {
                   3465: 	$res=$symb;
                   3466:     }
                   3467:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3468:     if (!$firstaccess) {
1.588     albertel 3469: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3470:     }
                   3471:     return 'already_set';
1.504     albertel 3472: }
                   3473: 
1.110     www      3474: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3475: 
                   3476: sub expirespread {
                   3477:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3478:     my $cid=$env{'request.course.id'}; 
1.110     www      3479:     if ($cid) {
                   3480:        my $now=time;
                   3481:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3482:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3483:                             $env{'course.'.$cid.'.num'}.
1.110     www      3484: 	        	    ':nohist_expirationdates:'.
                   3485:                             &escape($key).'='.$now,
1.620     albertel 3486:                             $env{'course.'.$cid.'.home'})
1.110     www      3487:     }
                   3488:     return 'ok';
1.14      www      3489: }
                   3490: 
1.109     www      3491: # ----------------------------------------------------- Devalidate Spreadsheets
                   3492: 
                   3493: sub devalidate {
1.325     www      3494:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3495:     my $cid=$env{'request.course.id'}; 
1.109     www      3496:     if ($cid) {
1.391     matthew  3497:         # delete the stored spreadsheets for
                   3498:         # - the student level sheet of this user in course's homespace
                   3499:         # - the assessment level sheet for this resource 
                   3500:         #   for this user in user's homespace
1.553     albertel 3501: 	# - current conditional state info
1.325     www      3502: 	my $key=$uname.':'.$udom.':';
1.109     www      3503:         my $status=
1.299     matthew  3504: 	    &del('nohist_calculatedsheets',
1.391     matthew  3505: 		 [$key.'studentcalc:'],
1.620     albertel 3506: 		 $env{'course.'.$cid.'.domain'},
                   3507: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3508: 		.' '.
                   3509: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3510: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3511:         unless ($status eq 'ok ok') {
                   3512:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3513:                     $uname.' at '.$udom.' for '.
1.109     www      3514: 		    $symb.': '.$status);
1.133     albertel 3515:         }
1.553     albertel 3516: 	&delenv('user.state.'.$cid);
1.109     www      3517:     }
                   3518: }
                   3519: 
1.265     albertel 3520: sub get_scalar {
                   3521:     my ($string,$end) = @_;
                   3522:     my $value;
                   3523:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3524: 	$value = $1;
                   3525:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3526: 	$value = $1;
                   3527:     }
                   3528:     return &unescape($value);
                   3529: }
                   3530: 
                   3531: sub array2str {
                   3532:   my (@array) = @_;
                   3533:   my $result=&arrayref2str(\@array);
                   3534:   $result=~s/^__ARRAY_REF__//;
                   3535:   $result=~s/__END_ARRAY_REF__$//;
                   3536:   return $result;
                   3537: }
                   3538: 
1.204     albertel 3539: sub arrayref2str {
                   3540:   my ($arrayref) = @_;
1.265     albertel 3541:   my $result='__ARRAY_REF__';
1.204     albertel 3542:   foreach my $elem (@$arrayref) {
1.265     albertel 3543:     if(ref($elem) eq 'ARRAY') {
                   3544:       $result.=&arrayref2str($elem).'&';
                   3545:     } elsif(ref($elem) eq 'HASH') {
                   3546:       $result.=&hashref2str($elem).'&';
                   3547:     } elsif(ref($elem)) {
                   3548:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3549:     } else {
                   3550:       $result.=&escape($elem).'&';
                   3551:     }
                   3552:   }
                   3553:   $result=~s/\&$//;
1.265     albertel 3554:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3555:   return $result;
                   3556: }
                   3557: 
1.168     albertel 3558: sub hash2str {
1.204     albertel 3559:   my (%hash) = @_;
                   3560:   my $result=&hashref2str(\%hash);
1.265     albertel 3561:   $result=~s/^__HASH_REF__//;
                   3562:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3563:   return $result;
                   3564: }
                   3565: 
                   3566: sub hashref2str {
                   3567:   my ($hashref)=@_;
1.265     albertel 3568:   my $result='__HASH_REF__';
1.800     albertel 3569:   foreach my $key (sort(keys(%$hashref))) {
                   3570:     if (ref($key) eq 'ARRAY') {
                   3571:       $result.=&arrayref2str($key).'=';
                   3572:     } elsif (ref($key) eq 'HASH') {
                   3573:       $result.=&hashref2str($key).'=';
                   3574:     } elsif (ref($key)) {
1.265     albertel 3575:       $result.='=';
1.800     albertel 3576:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3577:     } else {
1.800     albertel 3578: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3579:     }
                   3580: 
1.800     albertel 3581:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3582:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3583:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3584:       $result.=&hashref2str($hashref->{$key}).'&';
                   3585:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3586:        $result.='&';
1.800     albertel 3587:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3588:     } else {
1.800     albertel 3589:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3590:     }
                   3591:   }
1.168     albertel 3592:   $result=~s/\&$//;
1.265     albertel 3593:   $result .= '__END_HASH_REF__';
1.168     albertel 3594:   return $result;
                   3595: }
                   3596: 
                   3597: sub str2hash {
1.265     albertel 3598:     my ($string)=@_;
                   3599:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3600:     return %$hash;
                   3601: }
                   3602: 
                   3603: sub str2hashref {
1.168     albertel 3604:   my ($string) = @_;
1.265     albertel 3605: 
                   3606:   my %hash;
                   3607: 
                   3608:   if($string !~ /^__HASH_REF__/) {
                   3609:       if (! ($string eq '' || !defined($string))) {
                   3610: 	  $hash{'error'}='Not hash reference';
                   3611:       }
                   3612:       return (\%hash, $string);
                   3613:   }
                   3614: 
                   3615:   $string =~ s/^__HASH_REF__//;
                   3616: 
                   3617:   while($string !~ /^__END_HASH_REF__/) {
                   3618:       #key
                   3619:       my $key='';
                   3620:       if($string =~ /^__HASH_REF__/) {
                   3621:           ($key, $string)=&str2hashref($string);
                   3622:           if(defined($key->{'error'})) {
                   3623:               $hash{'error'}='Bad data';
                   3624:               return (\%hash, $string);
                   3625:           }
                   3626:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3627:           ($key, $string)=&str2arrayref($string);
                   3628:           if($key->[0] eq 'Array reference error') {
                   3629:               $hash{'error'}='Bad data';
                   3630:               return (\%hash, $string);
                   3631:           }
                   3632:       } else {
                   3633:           $string =~ s/^(.*?)=//;
1.267     albertel 3634: 	  $key=&unescape($1);
1.265     albertel 3635:       }
                   3636:       $string =~ s/^=//;
                   3637: 
                   3638:       #value
                   3639:       my $value='';
                   3640:       if($string =~ /^__HASH_REF__/) {
                   3641:           ($value, $string)=&str2hashref($string);
                   3642:           if(defined($value->{'error'})) {
                   3643:               $hash{'error'}='Bad data';
                   3644:               return (\%hash, $string);
                   3645:           }
                   3646:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3647:           ($value, $string)=&str2arrayref($string);
                   3648:           if($value->[0] eq 'Array reference error') {
                   3649:               $hash{'error'}='Bad data';
                   3650:               return (\%hash, $string);
                   3651:           }
                   3652:       } else {
                   3653: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3654:       }
                   3655:       $string =~ s/^&//;
                   3656: 
                   3657:       $hash{$key}=$value;
1.204     albertel 3658:   }
1.265     albertel 3659: 
                   3660:   $string =~ s/^__END_HASH_REF__//;
                   3661: 
                   3662:   return (\%hash, $string);
1.204     albertel 3663: }
                   3664: 
                   3665: sub str2array {
1.265     albertel 3666:     my ($string)=@_;
                   3667:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3668:     return @$array;
                   3669: }
                   3670: 
                   3671: sub str2arrayref {
1.204     albertel 3672:   my ($string) = @_;
1.265     albertel 3673:   my @array;
                   3674: 
                   3675:   if($string !~ /^__ARRAY_REF__/) {
                   3676:       if (! ($string eq '' || !defined($string))) {
                   3677: 	  $array[0]='Array reference error';
                   3678:       }
                   3679:       return (\@array, $string);
                   3680:   }
                   3681: 
                   3682:   $string =~ s/^__ARRAY_REF__//;
                   3683: 
                   3684:   while($string !~ /^__END_ARRAY_REF__/) {
                   3685:       my $value='';
                   3686:       if($string =~ /^__HASH_REF__/) {
                   3687:           ($value, $string)=&str2hashref($string);
                   3688:           if(defined($value->{'error'})) {
                   3689:               $array[0] ='Array reference error';
                   3690:               return (\@array, $string);
                   3691:           }
                   3692:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3693:           ($value, $string)=&str2arrayref($string);
                   3694:           if($value->[0] eq 'Array reference error') {
                   3695:               $array[0] ='Array reference error';
                   3696:               return (\@array, $string);
                   3697:           }
                   3698:       } else {
                   3699: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3700:       }
                   3701:       $string =~ s/^&//;
                   3702: 
                   3703:       push(@array, $value);
1.191     harris41 3704:   }
1.265     albertel 3705: 
                   3706:   $string =~ s/^__END_ARRAY_REF__//;
                   3707: 
                   3708:   return (\@array, $string);
1.168     albertel 3709: }
                   3710: 
1.167     albertel 3711: # -------------------------------------------------------------------Temp Store
                   3712: 
1.168     albertel 3713: sub tmpreset {
                   3714:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3715:   if (!$symb) {
                   3716:     $symb=&symbread();
1.620     albertel 3717:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3718:   }
                   3719:   $symb=escape($symb);
                   3720: 
1.620     albertel 3721:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3722:   $namespace=~s/\//\_/g;
                   3723:   $namespace=~s/\W//g;
                   3724: 
1.620     albertel 3725:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3726:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3727:   if ($domain eq 'public' && $stuname eq 'public') {
                   3728:       $stuname=$ENV{'REMOTE_ADDR'};
                   3729:   }
1.168     albertel 3730:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3731:   my %hash;
                   3732:   if (tie(%hash,'GDBM_File',
                   3733: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3734: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3735:     foreach my $key (keys(%hash)) {
1.180     albertel 3736:       if ($key=~ /:$symb/) {
1.168     albertel 3737: 	delete($hash{$key});
                   3738:       }
                   3739:     }
                   3740:   }
                   3741: }
                   3742: 
1.167     albertel 3743: sub tmpstore {
1.168     albertel 3744:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3745: 
                   3746:   if (!$symb) {
                   3747:     $symb=&symbread();
1.620     albertel 3748:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3749:   }
                   3750:   $symb=escape($symb);
                   3751: 
                   3752:   if (!$namespace) {
                   3753:     # I don't think we would ever want to store this for a course.
                   3754:     # it seems this will only be used if we don't have a course.
1.620     albertel 3755:     #$namespace=$env{'request.course.id'};
1.168     albertel 3756:     #if (!$namespace) {
1.620     albertel 3757:       $namespace=$env{'request.state'};
1.168     albertel 3758:     #}
                   3759:   }
                   3760:   $namespace=~s/\//\_/g;
                   3761:   $namespace=~s/\W//g;
1.620     albertel 3762:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3763:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3764:   if ($domain eq 'public' && $stuname eq 'public') {
                   3765:       $stuname=$ENV{'REMOTE_ADDR'};
                   3766:   }
1.168     albertel 3767:   my $now=time;
                   3768:   my %hash;
                   3769:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3770:   if (tie(%hash,'GDBM_File',
                   3771: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3772: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3773:     $hash{"version:$symb"}++;
                   3774:     my $version=$hash{"version:$symb"};
                   3775:     my $allkeys=''; 
                   3776:     foreach my $key (keys(%$storehash)) {
                   3777:       $allkeys.=$key.':';
1.591     albertel 3778:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3779:     }
                   3780:     $hash{"$version:$symb:timestamp"}=$now;
                   3781:     $allkeys.='timestamp';
                   3782:     $hash{"$version:keys:$symb"}=$allkeys;
                   3783:     if (untie(%hash)) {
                   3784:       return 'ok';
                   3785:     } else {
                   3786:       return "error:$!";
                   3787:     }
                   3788:   } else {
                   3789:     return "error:$!";
                   3790:   }
                   3791: }
1.167     albertel 3792: 
1.168     albertel 3793: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3794: 
1.168     albertel 3795: sub tmprestore {
                   3796:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3797: 
1.168     albertel 3798:   if (!$symb) {
                   3799:     $symb=&symbread();
1.620     albertel 3800:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3801:   }
                   3802:   $symb=escape($symb);
                   3803: 
1.620     albertel 3804:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3805: 
1.620     albertel 3806:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3807:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3808:   if ($domain eq 'public' && $stuname eq 'public') {
                   3809:       $stuname=$ENV{'REMOTE_ADDR'};
                   3810:   }
1.168     albertel 3811:   my %returnhash;
                   3812:   $namespace=~s/\//\_/g;
                   3813:   $namespace=~s/\W//g;
                   3814:   my %hash;
                   3815:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3816:   if (tie(%hash,'GDBM_File',
                   3817: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3818: 	  &GDBM_READER(),0640)) {
1.168     albertel 3819:     my $version=$hash{"version:$symb"};
                   3820:     $returnhash{'version'}=$version;
                   3821:     my $scope;
                   3822:     for ($scope=1;$scope<=$version;$scope++) {
                   3823:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3824:       my @keys=split(/:/,$vkeys);
                   3825:       my $key;
                   3826:       $returnhash{"$scope:keys"}=$vkeys;
                   3827:       foreach $key (@keys) {
1.591     albertel 3828: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3829: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3830:       }
                   3831:     }
1.168     albertel 3832:     if (!(untie(%hash))) {
                   3833:       return "error:$!";
                   3834:     }
                   3835:   } else {
                   3836:     return "error:$!";
                   3837:   }
                   3838:   return %returnhash;
1.167     albertel 3839: }
                   3840: 
1.9       www      3841: # ----------------------------------------------------------------------- Store
                   3842: 
                   3843: sub store {
1.124     www      3844:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3845:     my $home='';
                   3846: 
1.168     albertel 3847:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3848: 
1.213     www      3849:     $symb=&symbclean($symb);
1.122     albertel 3850:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3851: 
1.620     albertel 3852:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3853:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3854: 
                   3855:     &devalidate($symb,$stuname,$domain);
1.109     www      3856: 
                   3857:     $symb=escape($symb);
1.187     www      3858:     if (!$namespace) { 
1.620     albertel 3859:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3860:           return ''; 
                   3861:        } 
                   3862:     }
1.620     albertel 3863:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3864: 
                   3865:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3866:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3867: 
1.12      www      3868:     my $namevalue='';
1.800     albertel 3869:     foreach my $key (keys(%$storehash)) {
                   3870:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3871:     }
1.12      www      3872:     $namevalue=~s/\&$//;
1.187     www      3873:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3874:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3875: }
                   3876: 
1.47      www      3877: # -------------------------------------------------------------- Critical Store
                   3878: 
                   3879: sub cstore {
1.124     www      3880:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3881:     my $home='';
                   3882: 
1.168     albertel 3883:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3884: 
1.213     www      3885:     $symb=&symbclean($symb);
1.122     albertel 3886:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3887: 
1.620     albertel 3888:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3889:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3890: 
                   3891:     &devalidate($symb,$stuname,$domain);
1.109     www      3892: 
                   3893:     $symb=escape($symb);
1.187     www      3894:     if (!$namespace) { 
1.620     albertel 3895:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3896:           return ''; 
                   3897:        } 
                   3898:     }
1.620     albertel 3899:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3900: 
                   3901:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3902:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3903: 
1.47      www      3904:     my $namevalue='';
1.800     albertel 3905:     foreach my $key (keys(%$storehash)) {
                   3906:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3907:     }
1.47      www      3908:     $namevalue=~s/\&$//;
1.187     www      3909:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3910:     return critical
                   3911:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3912: }
                   3913: 
1.9       www      3914: # --------------------------------------------------------------------- Restore
                   3915: 
                   3916: sub restore {
1.124     www      3917:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3918:     my $home='';
                   3919: 
1.168     albertel 3920:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3921: 
1.122     albertel 3922:     if (!$symb) {
                   3923:       unless ($symb=escape(&symbread())) { return ''; }
                   3924:     } else {
1.213     www      3925:       $symb=&escape(&symbclean($symb));
1.122     albertel 3926:     }
1.188     www      3927:     if (!$namespace) { 
1.620     albertel 3928:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3929:           return ''; 
                   3930:        } 
                   3931:     }
1.620     albertel 3932:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3933:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3934:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3935:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3936: 
1.12      www      3937:     my %returnhash=();
1.800     albertel 3938:     foreach my $line (split(/\&/,$answer)) {
                   3939: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3940:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3941:     }
1.75      www      3942:     my $version;
                   3943:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3944:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3945:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3946:        }
1.75      www      3947:     }
1.13      www      3948:     return %returnhash;
1.34      www      3949: }
                   3950: 
                   3951: # ---------------------------------------------------------- Course Description
                   3952: 
                   3953: sub coursedescription {
1.731     albertel 3954:     my ($courseid,$args)=@_;
1.34      www      3955:     $courseid=~s/^\///;
1.49      www      3956:     $courseid=~s/\_/\//g;
1.34      www      3957:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3958:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3959:     my $normalid=$cdomain.'_'.$cnum;
                   3960:     # need to always cache even if we get errors otherwise we keep 
                   3961:     # trying and trying and trying to get the course description.
                   3962:     my %envhash=();
                   3963:     my %returnhash=();
1.731     albertel 3964:     
                   3965:     my $expiretime=600;
                   3966:     if ($env{'request.course.id'} eq $normalid) {
                   3967: 	$expiretime=120;
                   3968:     }
                   3969: 
                   3970:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3971:     if (!$args->{'freshen_cache'}
                   3972: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3973: 	foreach my $key (keys(%env)) {
                   3974: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3975: 	    my ($setting) = $1;
                   3976: 	    $returnhash{$setting} = $env{$key};
                   3977: 	}
                   3978: 	return %returnhash;
                   3979:     }
                   3980: 
                   3981:     # get the data agin
                   3982:     if (!$args->{'one_time'}) {
                   3983: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3984:     }
1.811     albertel 3985: 
1.34      www      3986:     if ($chome ne 'no_host') {
1.302     albertel 3987:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3988:        if (!exists($returnhash{'con_lost'})) {
                   3989:            $returnhash{'home'}= $chome;
                   3990: 	   $returnhash{'domain'} = $cdomain;
                   3991: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3992:            if (!defined($returnhash{'type'})) {
                   3993:                $returnhash{'type'} = 'Course';
                   3994:            }
1.130     albertel 3995:            while (my ($name,$value) = each %returnhash) {
1.53      www      3996:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3997:            }
1.270     www      3998:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3999:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4000: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4001:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4002:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4003:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4004:        }
                   4005:     }
1.731     albertel 4006:     if (!$args->{'one_time'}) {
1.949     raeburn  4007: 	&appenv(\%envhash);
1.731     albertel 4008:     }
1.302     albertel 4009:     return %returnhash;
1.461     www      4010: }
                   4011: 
1.1080    raeburn  4012: sub update_released_required {
                   4013:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4014:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4015:         $cid = $env{'request.course.id'};
                   4016:         $cdom = $env{'course.'.$cid.'.domain'};
                   4017:         $cnum = $env{'course.'.$cid.'.num'};
                   4018:         $chome = $env{'course.'.$cid.'.home'};
                   4019:     }
                   4020:     if ($needsrelease) {
                   4021:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4022:         my $needsupdate;
                   4023:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4024:             $needsupdate = 1;
                   4025:         } else {
                   4026:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4027:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4028:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4029:                 $needsupdate = 1;
                   4030:             }
                   4031:         }
                   4032:         if ($needsupdate) {
                   4033:             my %needshash = (
                   4034:                              'internal.releaserequired' => $needsrelease,
                   4035:                             );
                   4036:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4037:             if ($putresult eq 'ok') {
                   4038:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4039:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4040:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4041:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4042:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4043:                 }
                   4044:             }
                   4045:         }
                   4046:     }
                   4047:     return;
                   4048: }
                   4049: 
1.461     www      4050: # -------------------------------------------------See if a user is privileged
                   4051: 
                   4052: sub privileged {
                   4053:     my ($username,$domain)=@_;
                   4054:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4055: 			&homeserver($username,$domain));
1.1033    raeburn  4056:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4057:         ($rolesdump =~ /^error:/)) {
                   4058:         return 0;
                   4059:     }
1.461     www      4060:     my $now=time;
                   4061:     if ($rolesdump ne '') {
1.800     albertel 4062:         foreach my $entry (split(/&/,$rolesdump)) {
                   4063: 	    if ($entry!~/^rolesdef_/) {
                   4064: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4065: 		$area=~s/\_\w\w$//;
                   4066: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4067: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4068: 		    my $active=1;
                   4069: 		    if ($tend) {
                   4070: 			if ($tend<$now) { $active=0; }
                   4071: 		    }
                   4072: 		    if ($tstart) {
                   4073: 			if ($tstart>$now) { $active=0; }
                   4074: 		    }
                   4075: 		    if ($active) { return 1; }
                   4076: 		}
                   4077: 	    }
                   4078: 	}
                   4079:     }
                   4080:     return 0;
1.9       www      4081: }
1.1       albertel 4082: 
1.103     harris41 4083: # -------------------------------------------------------- Get user privileges
1.11      www      4084: 
                   4085: sub rolesinit {
                   4086:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4087:     my $now=time;
                   4088:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4089:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4090:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4091:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4092:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4093:         return \%userroles;
                   4094:     }
1.11      www      4095:     my %allroles=();
1.678     raeburn  4096:     my %allgroups=();   
1.11      www      4097: 
                   4098:     if ($rolesdump ne '') {
1.800     albertel 4099:         foreach my $entry (split(/&/,$rolesdump)) {
                   4100: 	  if ($entry!~/^rolesdef_/) {
                   4101:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4102: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4103:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4104: 	    if ($role=~/^cr/) { 
1.807     albertel 4105: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4106: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4107: 		    ($tend,$tstart)=split('_',$trest);
                   4108: 		} else {
                   4109: 		    $trole=$role;
                   4110: 		}
1.678     raeburn  4111:             } elsif ($role =~ m|^gr/|) {
                   4112:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4113:                 next if ($tstart eq '-1');
1.678     raeburn  4114:                 ($trole,$group_privs) = split(/\//,$trole);
                   4115:                 $group_privs = &unescape($group_privs);
1.587     albertel 4116: 	    } else {
                   4117: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4118: 	    }
1.743     albertel 4119: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4120: 					 $username);
                   4121: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4122:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4123:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4124:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4125: 		my $spec=$trole.'.'.$area;
                   4126: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4127: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4128:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4129:                 } elsif ($trole eq 'gr') {
                   4130:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4131: 		} else {
1.567     raeburn  4132:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4133: 		}
1.12      www      4134:             }
1.662     raeburn  4135:           }
1.191     harris41 4136:         }
1.743     albertel 4137:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4138:         $userroles{'user.adv'}    = $adv;
                   4139: 	$userroles{'user.author'} = $author;
1.620     albertel 4140:         $env{'user.adv'}=$adv;
1.11      www      4141:     }
1.743     albertel 4142:     return \%userroles;  
1.11      www      4143: }
                   4144: 
1.567     raeburn  4145: sub set_arearole {
                   4146:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4147: # log the associated role with the area
                   4148:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4149:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4150: }
                   4151: 
                   4152: sub custom_roleprivs {
                   4153:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4154:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4155:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4156:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4157:         my ($rdummy,$roledef)=
                   4158:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4159:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4160:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4161:             if (defined($syspriv)) {
1.1043    raeburn  4162:                 if ($trest =~ /^$match_community$/) {
                   4163:                     $syspriv =~ s/bre\&S//; 
                   4164:                 }
1.567     raeburn  4165:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4166:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4167:             }
                   4168:             if ($tdomain ne '') {
                   4169:                 if (defined($dompriv)) {
                   4170:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4171:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4172:                 }
                   4173:                 if (($trest ne '') && (defined($coursepriv))) {
                   4174:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4175:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4176:                 }
                   4177:             }
                   4178:         }
                   4179:     }
                   4180: }
                   4181: 
1.678     raeburn  4182: sub group_roleprivs {
                   4183:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4184:     my $access = 1;
                   4185:     my $now = time;
                   4186:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4187:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4188:     if ($access) {
1.811     albertel 4189:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4190:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4191:     }
                   4192: }
1.567     raeburn  4193: 
                   4194: sub standard_roleprivs {
                   4195:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4196:     if (defined($pr{$trole.':s'})) {
                   4197:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4198:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4199:     }
                   4200:     if ($tdomain ne '') {
                   4201:         if (defined($pr{$trole.':d'})) {
                   4202:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4203:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4204:         }
                   4205:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4206:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4207:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4208:         }
                   4209:     }
                   4210: }
                   4211: 
                   4212: sub set_userprivs {
1.1064    raeburn  4213:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4214:     my $author=0;
                   4215:     my $adv=0;
1.678     raeburn  4216:     my %grouproles = ();
                   4217:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4218:         my @groupkeys; 
1.1000    raeburn  4219:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4220:             push(@groupkeys,$role);
                   4221:         }
                   4222:         if (ref($groups_roles) eq 'HASH') {
                   4223:             foreach my $key (keys(%{$groups_roles})) {
                   4224:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4225:                     push(@groupkeys,$key);
                   4226:                 }
                   4227:             }
                   4228:         }
                   4229:         if (@groupkeys > 0) {
                   4230:             foreach my $role (@groupkeys) {
                   4231:                 my ($trole,$area,$sec,$extendedarea);
                   4232:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4233:                     $trole = $1;
                   4234:                     $area = $2;
                   4235:                     $sec = $3;
                   4236:                     $extendedarea = $area.$sec;
                   4237:                     if (exists($$allgroups{$area})) {
                   4238:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4239:                             my $spec = $trole.'.'.$extendedarea;
                   4240:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4241:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4242:                         }
1.678     raeburn  4243:                     }
                   4244:                 }
                   4245:             }
                   4246:         }
                   4247:     }
1.800     albertel 4248:     foreach my $group (keys(%grouproles)) {
                   4249:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4250:     }
1.800     albertel 4251:     foreach my $role (keys(%{$allroles})) {
                   4252:         my %thesepriv;
1.941     raeburn  4253:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4254:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4255:             if ($item ne '') {
                   4256:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4257:                 if ($restrictions eq '') {
                   4258:                     $thesepriv{$privilege}='F';
                   4259:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4260:                     $thesepriv{$privilege}.=$restrictions;
                   4261:                 }
                   4262:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4263:             }
                   4264:         }
                   4265:         my $thesestr='';
1.1104    raeburn  4266:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4267: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4268: 	}
                   4269:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4270:     }
                   4271:     return ($author,$adv);
                   4272: }
                   4273: 
1.994     raeburn  4274: sub role_status {
1.1104    raeburn  4275:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4276:     my @pwhere = ();
                   4277:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4278:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4279:         unless (!defined($$role) || $$role eq '') {
                   4280:             $$where=join('.',@pwhere);
                   4281:             $$trolecode=$$role.'.'.$$where;
                   4282:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4283:             $$tstatus='is';
1.1104    raeburn  4284:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4285:                 $$tstatus='future';
1.1034    raeburn  4286:                 if ($$tstart<$now) {
                   4287:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4288:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4289:                             my (%allroles,%allgroups,$group_privs,
                   4290:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4291:                             my %userroles = (
                   4292:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4293:                             );
1.1064    raeburn  4294:                             @rolecodes = ('cm'); 
1.1002    raeburn  4295:                             my $spec=$$role.'.'.$$where;
                   4296:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4297:                             if ($$role =~ /^cr\//) {
                   4298:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4299:                                 push(@rolecodes,'cr');
1.1002    raeburn  4300:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4301:                                 push(@rolecodes,$$role);
1.1002    raeburn  4302:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4303:                                                     $env{'user.name'});
1.1064    raeburn  4304:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4305:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4306:                                 $group_privs = &unescape($group_privs);
                   4307:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4308:                                 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  4309:                                 &get_groups_roles($tdomain,$trest,
                   4310:                                                   \%course_roles,\@rolecodes,
                   4311:                                                   \%groups_roles);
1.1002    raeburn  4312:                             } else {
1.1064    raeburn  4313:                                 push(@rolecodes,$$role);
1.1002    raeburn  4314:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4315:                             }
1.1064    raeburn  4316:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4317:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4318:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4319:                         }
                   4320:                     }
1.1034    raeburn  4321:                     $$tstatus = 'is';
1.1002    raeburn  4322:                 }
1.994     raeburn  4323:             }
                   4324:             if ($$tend) {
1.1104    raeburn  4325:                 if ($$tend<$update) {
1.994     raeburn  4326:                     $$tstatus='expired';
                   4327:                 } elsif ($$tend<$now) {
                   4328:                     $$tstatus='will_not';
                   4329:                 }
                   4330:             }
                   4331:         }
                   4332:     }
                   4333: }
                   4334: 
1.1104    raeburn  4335: sub get_groups_roles {
                   4336:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4337:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4338:                   (ref($rolecodes) eq 'ARRAY') && 
                   4339:                   (ref($groups_roles) eq 'HASH')); 
                   4340:     if (keys(%{$cdom_courseroles}) > 0) {
                   4341:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4342:         if ($cdom ne '' && $cnum ne '') {
                   4343:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4344:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4345:                     my $crsrole = $1;
                   4346:                     my $crssec = $2;
                   4347:                     if ($crsrole =~ /^cr/) {
                   4348:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4349:                             push(@{$rolecodes},'cr');
                   4350:                         }
                   4351:                     } else {
                   4352:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4353:                             push(@{$rolecodes},$crsrole);
                   4354:                         }
                   4355:                     }
                   4356:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4357:                     if ($crssec ne '') {
                   4358:                         $rolekey .= "/$crssec";
                   4359:                     }
                   4360:                     $rolekey .= './';
                   4361:                     $groups_roles->{$rolekey} = $rolecodes;
                   4362:                 }
                   4363:             }
                   4364:         }
                   4365:     }
                   4366:     return;
                   4367: }
                   4368: 
                   4369: sub delete_env_groupprivs {
                   4370:     my ($where,$courseroles,$possroles) = @_;
                   4371:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4372:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4373:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4374:         %{$courseroles->{$udom}} =
                   4375:             &get_my_roles('','','userroles',['active'],
                   4376:                           $possroles,[$udom],1);
                   4377:     }
                   4378:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4379:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4380:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4381:             my $area = '/'.$cdom.'/'.$cnum;
                   4382:             my $privkey = "user.priv.$crsrole.$area";
                   4383:             if ($crssec ne '') {
                   4384:                 $privkey .= '/'.$crssec;
                   4385:             }
                   4386:             $privkey .= ".$area/$group";
                   4387:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4388:         }
                   4389:     }
                   4390:     return;
                   4391: }
                   4392: 
1.994     raeburn  4393: sub check_adhoc_privs {
1.1104    raeburn  4394:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4395:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4396:     if ($env{$cckey}) {
                   4397:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4398:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4399:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4400:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4401:         }
                   4402:     } else {
1.1088    raeburn  4403:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4404:     }
                   4405: }
                   4406: 
                   4407: sub set_adhoc_privileges {
                   4408: # role can be cc or ca
1.1088    raeburn  4409:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4410:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4411:     my $spec = $role.'.'.$area;
                   4412:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4413:                                   $env{'user.name'});
                   4414:     my %ccrole = ();
                   4415:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4416:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4417:     &appenv(\%userroles,[$role,'cm']);
                   4418:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4419:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4420:         &appenv( {'request.role'        => $spec,
                   4421:                   'request.role.domain' => $dcdom,
                   4422:                   'request.course.sec'  => ''
                   4423:                  }
                   4424:                );
                   4425:         my $tadv=0;
                   4426:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4427:         &appenv({'request.role.adv'    => $tadv});
                   4428:     }
1.994     raeburn  4429: }
                   4430: 
1.12      www      4431: # --------------------------------------------------------------- get interface
                   4432: 
                   4433: sub get {
1.131     albertel 4434:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4435:    my $items='';
1.800     albertel 4436:    foreach my $item (@$storearr) {
                   4437:        $items.=&escape($item).'&';
1.191     harris41 4438:    }
1.12      www      4439:    $items=~s/\&$//;
1.620     albertel 4440:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4441:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4442:    my $uhome=&homeserver($uname,$udomain);
                   4443: 
1.133     albertel 4444:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4445:    my @pairs=split(/\&/,$rep);
1.273     albertel 4446:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4447:      return @pairs;
                   4448:    }
1.15      www      4449:    my %returnhash=();
1.42      www      4450:    my $i=0;
1.800     albertel 4451:    foreach my $item (@$storearr) {
                   4452:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4453:       $i++;
1.191     harris41 4454:    }
1.15      www      4455:    return %returnhash;
1.27      www      4456: }
                   4457: 
                   4458: # --------------------------------------------------------------- del interface
                   4459: 
                   4460: sub del {
1.133     albertel 4461:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4462:    my $items='';
1.800     albertel 4463:    foreach my $item (@$storearr) {
                   4464:        $items.=&escape($item).'&';
1.191     harris41 4465:    }
1.984     neumanie 4466: 
1.27      www      4467:    $items=~s/\&$//;
1.620     albertel 4468:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4469:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4470:    my $uhome=&homeserver($uname,$udomain);
                   4471:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4472: }
                   4473: 
                   4474: # -------------------------------------------------------------- dump interface
                   4475: 
                   4476: sub dump {
1.1086    raeburn  4477:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4478:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4479:     if (!$uname) { $uname=$env{'user.name'}; }
                   4480:     my $uhome=&homeserver($uname,$udomain);
                   4481:     if ($regexp) {
                   4482: 	$regexp=&escape($regexp);
                   4483:     } else {
                   4484: 	$regexp='.';
                   4485:     }
1.1086    raeburn  4486:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4487:     my @pairs=split(/\&/,$rep);
                   4488:     my %returnhash=();
1.1098    foxr     4489:     if (!($rep =~ /^error/ )) {
                   4490: 	foreach my $item (@pairs) {
                   4491: 	    my ($key,$value)=split(/=/,$item,2);
                   4492: 	    $key = &unescape($key);
                   4493: 	    next if ($key =~ /^error: 2 /);
                   4494: 	    $returnhash{$key}=&thaw_unescape($value);
                   4495: 	}
1.755     albertel 4496:     }
                   4497:     return %returnhash;
1.407     www      4498: }
                   4499: 
1.1098    foxr     4500: 
1.717     albertel 4501: # --------------------------------------------------------- dumpstore interface
                   4502: 
                   4503: sub dumpstore {
                   4504:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4505:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4506:    if (!$uname) { $uname=$env{'user.name'}; }
                   4507:    my $uhome=&homeserver($uname,$udomain);
                   4508:    if ($regexp) {
                   4509:        $regexp=&escape($regexp);
                   4510:    } else {
                   4511:        $regexp='.';
                   4512:    }
                   4513:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4514:    my @pairs=split(/\&/,$rep);
                   4515:    my %returnhash=();
                   4516:    foreach my $item (@pairs) {
                   4517:        my ($key,$value)=split(/=/,$item,2);
                   4518:        next if ($key =~ /^error: 2 /);
                   4519:        $returnhash{$key}=&thaw_unescape($value);
                   4520:    }
                   4521:    return %returnhash;
1.717     albertel 4522: }
                   4523: 
1.407     www      4524: # -------------------------------------------------------------- keys interface
                   4525: 
                   4526: sub getkeys {
                   4527:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4528:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4529:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4530:    my $uhome=&homeserver($uname,$udomain);
                   4531:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4532:    my @keyarray=();
1.800     albertel 4533:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4534:       next if ($key =~ /^error: 2 /);
1.800     albertel 4535:       push(@keyarray,&unescape($key));
1.407     www      4536:    }
                   4537:    return @keyarray;
1.318     matthew  4538: }
                   4539: 
1.319     matthew  4540: # --------------------------------------------------------------- currentdump
                   4541: sub currentdump {
1.328     matthew  4542:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4543:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4544:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4545:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4546:    my $uhome = &homeserver($sname,$sdom);
                   4547:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4548:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4549:    #
1.318     matthew  4550:    my %returnhash=();
1.319     matthew  4551:    #
                   4552:    if ($rep eq "unknown_cmd") { 
                   4553:        # an old lond will not know currentdump
                   4554:        # Do a dump and make it look like a currentdump
1.822     albertel 4555:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4556:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4557:        my %hash = @tmp;
                   4558:        @tmp=();
1.424     matthew  4559:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4560:    } else {
                   4561:        my @pairs=split(/\&/,$rep);
1.800     albertel 4562:        foreach my $pair (@pairs) {
                   4563:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4564:            my ($symb,$param) = split(/:/,$key);
                   4565:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4566:                                                         &thaw_unescape($value);
1.319     matthew  4567:        }
1.191     harris41 4568:    }
1.12      www      4569:    return %returnhash;
1.424     matthew  4570: }
                   4571: 
                   4572: sub convert_dump_to_currentdump{
                   4573:     my %hash = %{shift()};
                   4574:     my %returnhash;
                   4575:     # Code ripped from lond, essentially.  The only difference
                   4576:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4577:     # we might run in to problems with parameter names =~ /^v\./
                   4578:     while (my ($key,$value) = each(%hash)) {
                   4579:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4580: 	$symb  = &unescape($symb);
                   4581: 	$param = &unescape($param);
1.424     matthew  4582:         next if ($v eq 'version' || $symb eq 'keys');
                   4583:         next if (exists($returnhash{$symb}) &&
                   4584:                  exists($returnhash{$symb}->{$param}) &&
                   4585:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4586:         $returnhash{$symb}->{$param}=$value;
                   4587:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4588:     }
                   4589:     #
                   4590:     # Remove all of the keys in the hashes which keep track of
                   4591:     # the version of the parameter.
                   4592:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4593:         # use a foreach because we are going to delete from the hash.
                   4594:         foreach my $key (keys(%$param_hash)) {
                   4595:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4596:         }
                   4597:     }
                   4598:     return \%returnhash;
1.12      www      4599: }
                   4600: 
1.627     albertel 4601: # ------------------------------------------------------ critical inc interface
                   4602: 
                   4603: sub cinc {
                   4604:     return &inc(@_,'critical');
                   4605: }
                   4606: 
1.449     matthew  4607: # --------------------------------------------------------------- inc interface
                   4608: 
                   4609: sub inc {
1.627     albertel 4610:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4611:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4612:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4613:     my $uhome=&homeserver($uname,$udomain);
                   4614:     my $items='';
                   4615:     if (! ref($store)) {
                   4616:         # got a single value, so use that instead
                   4617:         $items = &escape($store).'=&';
                   4618:     } elsif (ref($store) eq 'SCALAR') {
                   4619:         $items = &escape($$store).'=&';        
                   4620:     } elsif (ref($store) eq 'ARRAY') {
                   4621:         $items = join('=&',map {&escape($_);} @{$store});
                   4622:     } elsif (ref($store) eq 'HASH') {
                   4623:         while (my($key,$value) = each(%{$store})) {
                   4624:             $items.= &escape($key).'='.&escape($value).'&';
                   4625:         }
                   4626:     }
                   4627:     $items=~s/\&$//;
1.627     albertel 4628:     if ($critical) {
                   4629: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4630:     } else {
                   4631: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4632:     }
1.449     matthew  4633: }
                   4634: 
1.12      www      4635: # --------------------------------------------------------------- put interface
                   4636: 
                   4637: sub put {
1.134     albertel 4638:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4640:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4641:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4642:    my $items='';
1.800     albertel 4643:    foreach my $item (keys(%$storehash)) {
                   4644:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4645:    }
1.12      www      4646:    $items=~s/\&$//;
1.134     albertel 4647:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4648: }
                   4649: 
1.631     albertel 4650: # ------------------------------------------------------------ newput interface
                   4651: 
                   4652: sub newput {
                   4653:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4655:    if (!$uname) { $uname=$env{'user.name'}; }
                   4656:    my $uhome=&homeserver($uname,$udomain);
                   4657:    my $items='';
                   4658:    foreach my $key (keys(%$storehash)) {
                   4659:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4660:    }
                   4661:    $items=~s/\&$//;
                   4662:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4663: }
                   4664: 
                   4665: # ---------------------------------------------------------  putstore interface
                   4666: 
1.524     raeburn  4667: sub putstore {
1.715     albertel 4668:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4669:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4670:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4671:    my $uhome=&homeserver($uname,$udomain);
                   4672:    my $items='';
1.715     albertel 4673:    foreach my $key (keys(%$storehash)) {
                   4674:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4675:    }
1.715     albertel 4676:    $items=~s/\&$//;
1.716     albertel 4677:    my $esc_symb=&escape($symb);
                   4678:    my $esc_v=&escape($version);
1.715     albertel 4679:    my $reply =
1.716     albertel 4680:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4681: 	      $uhome);
                   4682:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4683:        # gfall back to way things use to be done
1.715     albertel 4684:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4685: 			    $uname);
1.524     raeburn  4686:    }
1.715     albertel 4687:    return $reply;
                   4688: }
                   4689: 
                   4690: sub old_putstore {
1.716     albertel 4691:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4692:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4693:     if (!$uname) { $uname=$env{'user.name'}; }
                   4694:     my $uhome=&homeserver($uname,$udomain);
                   4695:     my %newstorehash;
1.800     albertel 4696:     foreach my $item (keys(%$storehash)) {
                   4697: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4698: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4699:     }
                   4700:     my $items='';
                   4701:     my %allitems = ();
1.800     albertel 4702:     foreach my $item (keys(%newstorehash)) {
                   4703: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4704: 	    my $key = $1.':keys:'.$2;
                   4705: 	    $allitems{$key} .= $3.':';
                   4706: 	}
1.800     albertel 4707: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4708:     }
1.800     albertel 4709:     foreach my $item (keys(%allitems)) {
                   4710: 	$allitems{$item} =~ s/\:$//;
                   4711: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4712:     }
                   4713:     $items=~s/\&$//;
                   4714:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4715: }
                   4716: 
1.47      www      4717: # ------------------------------------------------------ critical put interface
                   4718: 
                   4719: sub cput {
1.134     albertel 4720:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4721:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4722:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4723:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4724:    my $items='';
1.800     albertel 4725:    foreach my $item (keys(%$storehash)) {
                   4726:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4727:    }
1.47      www      4728:    $items=~s/\&$//;
1.134     albertel 4729:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4730: }
                   4731: 
                   4732: # -------------------------------------------------------------- eget interface
                   4733: 
                   4734: sub eget {
1.133     albertel 4735:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4736:    my $items='';
1.800     albertel 4737:    foreach my $item (@$storearr) {
                   4738:        $items.=&escape($item).'&';
1.191     harris41 4739:    }
1.12      www      4740:    $items=~s/\&$//;
1.620     albertel 4741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4742:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4743:    my $uhome=&homeserver($uname,$udomain);
                   4744:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4745:    my @pairs=split(/\&/,$rep);
                   4746:    my %returnhash=();
1.42      www      4747:    my $i=0;
1.800     albertel 4748:    foreach my $item (@$storearr) {
                   4749:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4750:       $i++;
1.191     harris41 4751:    }
1.12      www      4752:    return %returnhash;
                   4753: }
                   4754: 
1.667     albertel 4755: # ------------------------------------------------------------ tmpput interface
                   4756: sub tmpput {
1.802     raeburn  4757:     my ($storehash,$server,$context)=@_;
1.667     albertel 4758:     my $items='';
1.800     albertel 4759:     foreach my $item (keys(%$storehash)) {
                   4760: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4761:     }
                   4762:     $items=~s/\&$//;
1.802     raeburn  4763:     if (defined($context)) {
                   4764:         $items .= ':'.&escape($context);
                   4765:     }
1.667     albertel 4766:     return &reply("tmpput:$items",$server);
                   4767: }
                   4768: 
                   4769: # ------------------------------------------------------------ tmpget interface
                   4770: sub tmpget {
1.688     albertel 4771:     my ($token,$server)=@_;
                   4772:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4773:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4774:     my %returnhash;
                   4775:     foreach my $item (split(/\&/,$rep)) {
                   4776: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4777:         next if ($key =~ /^error: 2 /);
1.667     albertel 4778: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4779:     }
                   4780:     return %returnhash;
                   4781: }
                   4782: 
1.688     albertel 4783: # ------------------------------------------------------------ tmpget interface
                   4784: sub tmpdel {
                   4785:     my ($token,$server)=@_;
                   4786:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4787:     return &reply("tmpdel:$token",$server);
                   4788: }
                   4789: 
1.765     albertel 4790: # -------------------------------------------------- portfolio access checking
                   4791: 
                   4792: sub portfolio_access {
1.766     albertel 4793:     my ($requrl) = @_;
1.765     albertel 4794:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4795:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4796:     if ($result) {
                   4797:         my %setters;
                   4798:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4799:             my ($startblock,$endblock) =
                   4800:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4801:             if ($startblock && $endblock) {
                   4802:                 return 'B';
                   4803:             }
                   4804:         } else {
                   4805:             my ($startblock,$endblock) =
                   4806:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4807:             if ($startblock && $endblock) {
                   4808:                 return 'B';
                   4809:             }
                   4810:         }
                   4811:     }
1.765     albertel 4812:     if ($result eq 'ok') {
1.766     albertel 4813:        return 'F';
1.765     albertel 4814:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4815:        return 'A';
1.765     albertel 4816:     }
1.766     albertel 4817:     return '';
1.765     albertel 4818: }
                   4819: 
                   4820: sub get_portfolio_access {
1.767     albertel 4821:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4822: 
                   4823:     if (!ref($access_hash)) {
                   4824: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4825: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4826: 						   $file_name);
                   4827: 	$access_hash = $access_controls{$file_name};
                   4828:     }
                   4829: 
1.765     albertel 4830:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4831:     my $now = time;
                   4832:     if (ref($access_hash) eq 'HASH') {
                   4833:         foreach my $key (keys(%{$access_hash})) {
                   4834:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4835:             if ($start > $now) {
                   4836:                 next;
                   4837:             }
                   4838:             if ($end && $end<$now) {
                   4839:                 next;
                   4840:             }
                   4841:             if ($scope eq 'public') {
                   4842:                 $public = $key;
                   4843:                 last;
                   4844:             } elsif ($scope eq 'guest') {
                   4845:                 $guest = $key;
                   4846:             } elsif ($scope eq 'domains') {
                   4847:                 push(@domains,$key);
                   4848:             } elsif ($scope eq 'users') {
                   4849:                 push(@users,$key);
                   4850:             } elsif ($scope eq 'course') {
                   4851:                 push(@courses,$key);
                   4852:             } elsif ($scope eq 'group') {
                   4853:                 push(@groups,$key);
                   4854:             }
                   4855:         }
                   4856:         if ($public) {
                   4857:             return 'ok';
                   4858:         }
                   4859:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4860:             if ($guest) {
                   4861:                 return $guest;
                   4862:             }
                   4863:         } else {
                   4864:             if (@domains > 0) {
                   4865:                 foreach my $domkey (@domains) {
                   4866:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4867:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4868:                             return 'ok';
                   4869:                         }
                   4870:                     }
                   4871:                 }
                   4872:             }
                   4873:             if (@users > 0) {
                   4874:                 foreach my $userkey (@users) {
1.865     raeburn  4875:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4876:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4877:                             if (ref($item) eq 'HASH') {
                   4878:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4879:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4880:                                     return 'ok';
                   4881:                                 }
                   4882:                             }
                   4883:                         }
                   4884:                     } 
1.765     albertel 4885:                 }
                   4886:             }
                   4887:             my %roleshash;
                   4888:             my @courses_and_groups = @courses;
                   4889:             push(@courses_and_groups,@groups); 
                   4890:             if (@courses_and_groups > 0) {
                   4891:                 my (%allgroups,%allroles); 
                   4892:                 my ($start,$end,$role,$sec,$group);
                   4893:                 foreach my $envkey (%env) {
1.1060    raeburn  4894:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4895:                         my $cid = $2.'_'.$3; 
                   4896:                         if ($1 eq 'gr') {
                   4897:                             $group = $4;
                   4898:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4899:                         } else {
                   4900:                             if ($4 eq '') {
                   4901:                                 $sec = 'none';
                   4902:                             } else {
                   4903:                                 $sec = $4;
                   4904:                             }
                   4905:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4906:                         }
1.811     albertel 4907:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4908:                         my $cid = $2.'_'.$3;
                   4909:                         if ($4 eq '') {
                   4910:                             $sec = 'none';
                   4911:                         } else {
                   4912:                             $sec = $4;
                   4913:                         }
                   4914:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4915:                     }
                   4916:                 }
                   4917:                 if (keys(%allroles) == 0) {
                   4918:                     return;
                   4919:                 }
                   4920:                 foreach my $key (@courses_and_groups) {
                   4921:                     my %content = %{$$access_hash{$key}};
                   4922:                     my $cnum = $content{'number'};
                   4923:                     my $cdom = $content{'domain'};
                   4924:                     my $cid = $cdom.'_'.$cnum;
                   4925:                     if (!exists($allroles{$cid})) {
                   4926:                         next;
                   4927:                     }    
                   4928:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4929:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4930:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4931:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4932:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4933:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4934:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4935:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4936:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4937:                                         if (grep/^all$/,@sections) {
                   4938:                                             return 'ok';
                   4939:                                         } else {
                   4940:                                             if (grep/^$sec$/,@sections) {
                   4941:                                                 return 'ok';
                   4942:                                             }
                   4943:                                         }
                   4944:                                     }
                   4945:                                 }
                   4946:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4947:                                     if (grep/^none$/,@groups) {
                   4948:                                         return 'ok';
                   4949:                                     }
                   4950:                                 } else {
                   4951:                                     if (grep/^all$/,@groups) {
                   4952:                                         return 'ok';
                   4953:                                     } 
                   4954:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4955:                                         if (grep/^$group$/,@groups) {
                   4956:                                             return 'ok';
                   4957:                                         }
                   4958:                                     }
                   4959:                                 } 
                   4960:                             }
                   4961:                         }
                   4962:                     }
                   4963:                 }
                   4964:             }
                   4965:             if ($guest) {
                   4966:                 return $guest;
                   4967:             }
                   4968:         }
                   4969:     }
                   4970:     return;
                   4971: }
                   4972: 
                   4973: sub course_group_datechecker {
                   4974:     my ($dates,$now,$status) = @_;
                   4975:     my ($start,$end) = split(/\./,$dates);
                   4976:     if (!$start && !$end) {
                   4977:         return 'ok';
                   4978:     }
                   4979:     if (grep/^active$/,@{$status}) {
                   4980:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4981:             return 'ok';
                   4982:         }
                   4983:     }
                   4984:     if (grep/^previous$/,@{$status}) {
                   4985:         if ($end > $now ) {
                   4986:             return 'ok';
                   4987:         }
                   4988:     }
                   4989:     if (grep/^future$/,@{$status}) {
                   4990:         if ($start > $now) {
                   4991:             return 'ok';
                   4992:         }
                   4993:     }
                   4994:     return; 
                   4995: }
                   4996: 
                   4997: sub parse_portfolio_url {
                   4998:     my ($url) = @_;
                   4999: 
                   5000:     my ($type,$udom,$unum,$group,$file_name);
                   5001:     
1.823     albertel 5002:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5003: 	$type = 1;
                   5004:         $udom = $1;
                   5005:         $unum = $2;
                   5006:         $file_name = $3;
1.823     albertel 5007:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5008: 	$type = 2;
                   5009:         $udom = $1;
                   5010:         $unum = $2;
                   5011:         $group = $3;
                   5012:         $file_name = $3.'/'.$4;
                   5013:     }
                   5014:     if (wantarray) {
                   5015: 	return ($type,$udom,$unum,$file_name,$group);
                   5016:     }
                   5017:     return $type;
                   5018: }
                   5019: 
                   5020: sub is_portfolio_url {
                   5021:     my ($url) = @_;
                   5022:     return scalar(&parse_portfolio_url($url));
                   5023: }
                   5024: 
1.798     raeburn  5025: sub is_portfolio_file {
                   5026:     my ($file) = @_;
1.820     raeburn  5027:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5028:         return 1;
                   5029:     }
                   5030:     return;
                   5031: }
                   5032: 
1.976     raeburn  5033: sub usertools_access {
1.1084    raeburn  5034:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5035:     my ($access,%tools);
                   5036:     if ($context eq '') {
                   5037:         $context = 'tools';
                   5038:     }
                   5039:     if ($context eq 'requestcourses') {
                   5040:         %tools = (
                   5041:                       official   => 1,
                   5042:                       unofficial => 1,
1.1006    raeburn  5043:                       community  => 1,
1.985     raeburn  5044:                  );
                   5045:     } else {
                   5046:         %tools = (
                   5047:                       aboutme   => 1,
                   5048:                       blog      => 1,
                   5049:                       portfolio => 1,
                   5050:                  );
                   5051:     }
1.976     raeburn  5052:     return if (!defined($tools{$tool}));
                   5053: 
                   5054:     if ((!defined($udom)) || (!defined($uname))) {
                   5055:         $udom = $env{'user.domain'};
                   5056:         $uname = $env{'user.name'};
                   5057:     }
                   5058: 
1.978     raeburn  5059:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5060:         if ($action ne 'reload') {
1.985     raeburn  5061:             if ($context eq 'requestcourses') {
                   5062:                 return $env{'environment.canrequest.'.$tool};
                   5063:             } else {
                   5064:                 return $env{'environment.availabletools.'.$tool};
                   5065:             }
                   5066:         }
1.976     raeburn  5067:     }
                   5068: 
                   5069:     my ($toolstatus,$inststatus);
                   5070: 
1.985     raeburn  5071:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5072:          ($action ne 'reload')) {
                   5073:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5074:         $inststatus = $env{'environment.inststatus'};
                   5075:     } else {
1.1084    raeburn  5076:         if (ref($userenvref) eq 'HASH') {
                   5077:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5078:             $inststatus = $userenvref->{'inststatus'};
                   5079:         } else {
                   5080:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5081:             $toolstatus = $userenv{$context.'.'.$tool};
                   5082:             $inststatus = $userenv{'inststatus'};
                   5083:         }
1.976     raeburn  5084:     }
                   5085: 
                   5086:     if ($toolstatus ne '') {
                   5087:         if ($toolstatus) {
                   5088:             $access = 1;
                   5089:         } else {
                   5090:             $access = 0;
                   5091:         }
                   5092:         return $access;
                   5093:     }
                   5094: 
1.1084    raeburn  5095:     my ($is_adv,%domdef);
                   5096:     if (ref($is_advref) eq 'HASH') {
                   5097:         $is_adv = $is_advref->{'is_adv'};
                   5098:     } else {
                   5099:         $is_adv = &is_advanced_user($udom,$uname);
                   5100:     }
                   5101:     if (ref($domdefref) eq 'HASH') {
                   5102:         %domdef = %{$domdefref};
                   5103:     } else {
                   5104:         %domdef = &get_domain_defaults($udom);
                   5105:     }
1.976     raeburn  5106:     if (ref($domdef{$tool}) eq 'HASH') {
                   5107:         if ($is_adv) {
                   5108:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5109:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5110:                     $access = 1;
                   5111:                 } else {
                   5112:                     $access = 0;
                   5113:                 }
                   5114:                 return $access;
                   5115:             }
                   5116:         }
                   5117:         if ($inststatus ne '') {
                   5118:             my ($hasaccess,$hasnoaccess);
                   5119:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5120:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5121:                     if ($domdef{$tool}{$affiliation}) {
                   5122:                         $hasaccess = 1;
                   5123:                     } else {
                   5124:                         $hasnoaccess = 1;
                   5125:                     }
                   5126:                 }
                   5127:             }
                   5128:             if ($hasaccess || $hasnoaccess) {
                   5129:                 if ($hasaccess) {
                   5130:                     $access = 1;
                   5131:                 } elsif ($hasnoaccess) {
                   5132:                     $access = 0; 
                   5133:                 }
                   5134:                 return $access;
                   5135:             }
                   5136:         } else {
                   5137:             if ($domdef{$tool}{'default'} ne '') {
                   5138:                 if ($domdef{$tool}{'default'}) {
                   5139:                     $access = 1;
                   5140:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5141:                     $access = 0;
                   5142:                 }
                   5143:                 return $access;
                   5144:             }
                   5145:         }
                   5146:     } else {
1.985     raeburn  5147:         if ($context eq 'tools') {
                   5148:             $access = 1;
                   5149:         } else {
                   5150:             $access = 0;
                   5151:         }
1.976     raeburn  5152:         return $access;
                   5153:     }
                   5154: }
                   5155: 
1.1050    raeburn  5156: sub is_course_owner {
                   5157:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5158:     if (($udom eq '') || ($uname eq '')) {
                   5159:         $udom = $env{'user.domain'};
                   5160:         $uname = $env{'user.name'};
                   5161:     }
                   5162:     unless (($udom eq '') || ($uname eq '')) {
                   5163:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5164:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5165:                 return 1;
                   5166:             } else {
                   5167:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5168:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5169:                     return 1;
                   5170:                 }
                   5171:             }
                   5172:         }
                   5173:     }
                   5174:     return;
                   5175: }
                   5176: 
1.976     raeburn  5177: sub is_advanced_user {
                   5178:     my ($udom,$uname) = @_;
1.1085    raeburn  5179:     if ($udom ne '' && $uname ne '') {
                   5180:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5181:             return $env{'user.adv'};  
                   5182:         }
                   5183:     }
1.976     raeburn  5184:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5185:     my %allroles;
                   5186:     my $is_adv;
                   5187:     foreach my $role (keys(%roleshash)) {
                   5188:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5189:         my $area = '/'.$tdomain.'/'.$trest;
                   5190:         if ($sec ne '') {
                   5191:             $area .= '/'.$sec;
                   5192:         }
                   5193:         if (($area ne '') && ($trole ne '')) {
                   5194:             my $spec=$trole.'.'.$area;
                   5195:             if ($trole =~ /^cr\//) {
                   5196:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5197:             } elsif ($trole ne 'gr') {
                   5198:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5199:             }
                   5200:         }
                   5201:     }
                   5202:     foreach my $role (keys(%allroles)) {
                   5203:         last if ($is_adv);
                   5204:         foreach my $item (split(/:/,$allroles{$role})) {
                   5205:             if ($item ne '') {
                   5206:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5207:                 if ($privilege eq 'adv') {
                   5208:                     $is_adv = 1;
                   5209:                     last;
                   5210:                 }
                   5211:             }
                   5212:         }
                   5213:     }
                   5214:     return $is_adv;
                   5215: }
1.798     raeburn  5216: 
1.1035    raeburn  5217: sub check_can_request {
1.1036    raeburn  5218:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5219:     my $canreq = 0;
                   5220:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5221:     my @options = ('approval','validate','autolimit');
                   5222:     my $optregex = join('|',@options);
                   5223:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5224:         foreach my $type (@{$types}) {
                   5225:             if (&usertools_access($env{'user.name'},
                   5226:                                   $env{'user.domain'},
                   5227:                                   $type,undef,'requestcourses')) {
                   5228:                 $canreq ++;
1.1036    raeburn  5229:                 if (ref($request_domains) eq 'HASH') {
                   5230:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5231:                 }
1.1035    raeburn  5232:                 if ($dom eq $env{'user.domain'}) {
                   5233:                     $can_request->{$type} = 1;
                   5234:                 }
                   5235:             }
                   5236:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5237:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5238:                 if (@curr > 0) {
1.1036    raeburn  5239:                     foreach my $item (@curr) {
                   5240:                         if (ref($request_domains) eq 'HASH') {
                   5241:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5242:                             if ($otherdom ne '') {
                   5243:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5244:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5245:                                         push(@{$request_domains->{$type}},$otherdom);
                   5246:                                     }
                   5247:                                 } else {
                   5248:                                     push(@{$request_domains->{$type}},$otherdom);
                   5249:                                 }
                   5250:                             }
                   5251:                         }
                   5252:                     }
                   5253:                     unless($dom eq $env{'user.domain'}) {
                   5254:                         $canreq ++;
1.1035    raeburn  5255:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5256:                             $can_request->{$type} = 1;
                   5257:                         }
                   5258:                     }
                   5259:                 }
                   5260:             }
                   5261:         }
                   5262:     }
                   5263:     return $canreq;
                   5264: }
                   5265: 
1.341     www      5266: # ---------------------------------------------- Custom access rule evaluation
                   5267: 
                   5268: sub customaccess {
                   5269:     my ($priv,$uri)=@_;
1.807     albertel 5270:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5271:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5272:     $udom = &LONCAPA::clean_domain($udom);
                   5273:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5274:     my $access=0;
1.800     albertel 5275:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5276: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5277: 	if ($type eq 'user') {
                   5278: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5279: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5280: 		if ($tdom) {
                   5281: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5282: 		}
1.896     albertel 5283: 		if ($tuname) {
                   5284: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5285: 		}
                   5286: 		$access=($effect eq 'allow');
                   5287: 		last;
                   5288: 	    }
                   5289: 	} else {
                   5290: 	    if ($role) {
                   5291: 		if ($role ne $urole) { next; }
                   5292: 	    }
                   5293: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5294: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5295: 		if ($tdom) {
                   5296: 		    if ($tdom ne $udom) { next; }
                   5297: 		}
                   5298: 		if ($tcrs) {
                   5299: 		    if ($tcrs ne $ucrs) { next; }
                   5300: 		}
                   5301: 		if ($tsec) {
                   5302: 		    if ($tsec ne $usec) { next; }
                   5303: 		}
                   5304: 		$access=($effect eq 'allow');
                   5305: 		last;
                   5306: 	    }
                   5307: 	    if ($realm eq '' && $role eq '') {
                   5308: 		$access=($effect eq 'allow');
                   5309: 	    }
1.402     bowersj2 5310: 	}
1.341     www      5311:     }
                   5312:     return $access;
                   5313: }
                   5314: 
1.103     harris41 5315: # ------------------------------------------------- Check for a user privilege
1.12      www      5316: 
                   5317: sub allowed {
1.810     raeburn  5318:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5319:     my $ver_orguri=$uri;
1.439     www      5320:     $uri=&deversion($uri);
1.152     www      5321:     my $orguri=$uri;
1.52      www      5322:     $uri=&declutter($uri);
1.809     raeburn  5323: 
1.810     raeburn  5324:     if ($priv eq 'evb') {
                   5325: # Evade communication block restrictions for specified role in a course
                   5326:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5327:             return $1;
                   5328:         } else {
                   5329:             return;
                   5330:         }
                   5331:     }
                   5332: 
1.620     albertel 5333:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5334: # Free bre access to adm and meta resources
1.775     albertel 5335:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5336: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5337: 	&& ($priv eq 'bre')) {
1.14      www      5338: 	return 'F';
1.159     www      5339:     }
                   5340: 
1.545     banghart 5341: # Free bre access to user's own portfolio contents
1.714     raeburn  5342:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5343:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5344: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5345:         my %setters;
                   5346:         my ($startblock,$endblock) = 
                   5347:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5348:         if ($startblock && $endblock) {
                   5349:             return 'B';
                   5350:         } else {
                   5351:             return 'F';
                   5352:         }
1.545     banghart 5353:     }
                   5354: 
1.762     raeburn  5355: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5356:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5357:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5358:         if (exists($env{'request.course.id'})) {
                   5359:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5360:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5361:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5362:                 my $courseprivid=$env{'request.course.id'};
                   5363:                 $courseprivid=~s/\_/\//;
                   5364:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5365:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5366:                     return $1; 
1.762     raeburn  5367:                 } else {
                   5368:                     if ($env{'request.course.sec'}) {
                   5369:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5370:                     }
                   5371:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5372:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5373:                         return $2;
                   5374:                     }
1.714     raeburn  5375:                 }
                   5376:             }
                   5377:         }
                   5378:     }
                   5379: 
1.159     www      5380: # Free bre to public access
                   5381: 
                   5382:     if ($priv eq 'bre') {
1.238     www      5383:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5384: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5385:            return 'F'; 
                   5386:         }
1.238     www      5387:         if ($copyright eq 'priv') {
                   5388:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5389: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5390: 		return '';
                   5391:             }
                   5392:         }
                   5393:         if ($copyright eq 'domain') {
                   5394:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5395: 	    unless (($env{'user.domain'} eq $1) ||
                   5396:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5397: 		return '';
                   5398:             }
1.262     matthew  5399:         }
1.620     albertel 5400:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5401:             # Library role, so allow browsing of resources in this domain.
                   5402:             return 'F';
1.238     www      5403:         }
1.341     www      5404:         if ($copyright eq 'custom') {
                   5405: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5406:         }
1.14      www      5407:     }
1.264     matthew  5408:     # Domain coordinator is trying to create a course
1.620     albertel 5409:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5410:         # uri is the requested domain in this case.
                   5411:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5412:         # a role of dc for the domain in question.
1.620     albertel 5413:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5414:     }
1.29      www      5415: 
1.52      www      5416:     my $thisallowed='';
                   5417:     my $statecond=0;
                   5418:     my $courseprivid='';
                   5419: 
1.1039    raeburn  5420:     my $ownaccess;
1.1043    raeburn  5421:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5422:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5423:         if ($uri eq '') {
                   5424:             $ownaccess = 1;
                   5425:         } else {
                   5426:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5427:                 my $udom = $env{'user.domain'};
                   5428:                 my $uname = $env{'user.name'};
                   5429:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5430:                     $ownaccess = 1;
1.1040    raeburn  5431:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5432:                     unless ($uri =~ m{\.\./}) {
                   5433:                         $ownaccess = 1;
                   5434:                     }
                   5435:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5436:                     my $now = time;
                   5437:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5438:                         my $adom = $1;
                   5439:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5440:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5441:                                 my ($start,$end) = split('.',$env{$key});
                   5442:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5443:                                     $ownaccess = 1;
                   5444:                                     last;
                   5445:                                 }
                   5446:                             }
                   5447:                         }
                   5448:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5449:                         my $adom = $1;
                   5450:                         my $aname = $2;
1.1042    raeburn  5451:                         foreach my $role ('ca','aa') { 
                   5452:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5453:                                 my ($start,$end) =
                   5454:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5455:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5456:                                     $ownaccess = 1;
                   5457:                                     last;
                   5458:                                 }
1.1039    raeburn  5459:                             }
                   5460:                         }
                   5461:                     }
                   5462:                 }
                   5463:             }
                   5464:         }
                   5465:     }
                   5466: 
1.52      www      5467: # Course
                   5468: 
1.620     albertel 5469:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5470:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5471:             $thisallowed.=$1;
                   5472:         }
1.52      www      5473:     }
1.29      www      5474: 
1.52      www      5475: # Domain
                   5476: 
1.620     albertel 5477:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5478:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5479:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5480:             $thisallowed.=$1;
                   5481:         }
1.12      www      5482:     }
1.52      www      5483: 
                   5484: # Course: uri itself is a course
1.66      www      5485:     my $courseuri=$uri;
                   5486:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5487:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5488: 
1.620     albertel 5489:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5490:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5491:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5492:             $thisallowed.=$1;
                   5493:         }
1.12      www      5494:     }
1.29      www      5495: 
1.665     albertel 5496: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5497: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5498:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5499: 	$thisallowed='';
1.671     raeburn  5500:         my ($match)=&is_on_map($uri);
                   5501:         if ($match) {
                   5502:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5503:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5504:                 $thisallowed.=$1;
                   5505:             }
                   5506:         } else {
1.705     albertel 5507:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5508:             if ($refuri) {
                   5509:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5510:                     $thisallowed='F';
1.671     raeburn  5511:                 } else {
                   5512:                     $refuri=&declutter($refuri);
                   5513:                     my ($match) = &is_on_map($refuri);
                   5514:                     if ($match) {
                   5515:                         $thisallowed='F';
                   5516:                     }
1.669     raeburn  5517:                 }
1.671     raeburn  5518:             }
                   5519:         }
1.314     www      5520:     }
1.492     albertel 5521: 
1.766     albertel 5522:     if ($priv eq 'bre'
                   5523: 	&& $thisallowed ne 'F' 
                   5524: 	&& $thisallowed ne '2'
                   5525: 	&& &is_portfolio_url($uri)) {
                   5526: 	$thisallowed = &portfolio_access($uri);
                   5527:     }
                   5528:     
1.52      www      5529: # Full access at system, domain or course-wide level? Exit.
1.29      www      5530:     if ($thisallowed=~/F/) {
                   5531: 	return 'F';
                   5532:     }
                   5533: 
1.52      www      5534: # If this is generating or modifying users, exit with special codes
1.29      www      5535: 
1.643     www      5536:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5537: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5538: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5539: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5540: 	    unless ($auname) { return $thisallowed; }
                   5541: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5542: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5543: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5544: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5545: 	}
1.52      www      5546: 	return $thisallowed;
                   5547:     }
                   5548: #
1.103     harris41 5549: # Gathered so far: system, domain and course wide privileges
1.52      www      5550: #
                   5551: # Course: See if uri or referer is an individual resource that is part of 
                   5552: # the course
                   5553: 
1.620     albertel 5554:     if ($env{'request.course.id'}) {
1.232     www      5555: 
1.620     albertel 5556:        $courseprivid=$env{'request.course.id'};
                   5557:        if ($env{'request.course.sec'}) {
                   5558:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5559:        }
                   5560:        $courseprivid=~s/\_/\//;
                   5561:        my $checkreferer=1;
1.232     www      5562:        my ($match,$cond)=&is_on_map($uri);
                   5563:        if ($match) {
                   5564:            $statecond=$cond;
1.620     albertel 5565:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5566:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5567:                $thisallowed.=$1;
                   5568:                $checkreferer=0;
                   5569:            }
1.29      www      5570:        }
1.83      www      5571:        
1.148     www      5572:        if ($checkreferer) {
1.620     albertel 5573: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5574:             unless ($refuri) {
1.800     albertel 5575:                 foreach my $key (keys(%env)) {
                   5576: 		    if ($key=~/^httpref\..*\*/) {
                   5577: 			my $pattern=$key;
1.156     www      5578:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5579:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5580:                         $pattern=~s/\//\\\//g;
1.152     www      5581:                         if ($orguri=~/$pattern/) {
1.800     albertel 5582: 			    $refuri=$env{$key};
1.148     www      5583:                         }
                   5584:                     }
1.191     harris41 5585:                 }
1.148     www      5586:             }
1.232     www      5587: 
1.148     www      5588:          if ($refuri) { 
1.152     www      5589: 	  $refuri=&declutter($refuri);
1.232     www      5590:           my ($match,$cond)=&is_on_map($refuri);
                   5591:             if ($match) {
                   5592:               my $refstatecond=$cond;
1.620     albertel 5593:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5594:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5595:                   $thisallowed.=$1;
1.53      www      5596:                   $uri=$refuri;
                   5597:                   $statecond=$refstatecond;
1.52      www      5598:               }
                   5599:           }
1.148     www      5600:         }
1.29      www      5601:        }
1.52      www      5602:    }
1.29      www      5603: 
1.52      www      5604: #
1.103     harris41 5605: # Gathered now: all privileges that could apply, and condition number
1.52      www      5606: # 
                   5607: #
                   5608: # Full or no access?
                   5609: #
1.29      www      5610: 
1.52      www      5611:     if ($thisallowed=~/F/) {
                   5612: 	return 'F';
                   5613:     }
1.29      www      5614: 
1.52      www      5615:     unless ($thisallowed) {
                   5616:         return '';
                   5617:     }
1.29      www      5618: 
1.52      www      5619: # Restrictions exist, deal with them
                   5620: #
                   5621: #   C:according to course preferences
                   5622: #   R:according to resource settings
                   5623: #   L:unless locked
                   5624: #   X:according to user session state
                   5625: #
                   5626: 
                   5627: # Possibly locked functionality, check all courses
1.54      www      5628: # Locks might take effect only after 10 minutes cache expiration for other
                   5629: # courses, and 2 minutes for current course
1.52      www      5630: 
                   5631:     my $envkey;
                   5632:     if ($thisallowed=~/L/) {
1.1000    raeburn  5633:         foreach $envkey (keys(%env)) {
1.54      www      5634:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5635:                my $courseid=$2;
                   5636:                my $roleid=$1.'.'.$2;
1.92      www      5637:                $courseid=~s/^\///;
1.54      www      5638:                my $expiretime=600;
1.620     albertel 5639:                if ($env{'request.role'} eq $roleid) {
1.54      www      5640: 		  $expiretime=120;
                   5641:                }
                   5642: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5643:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5644:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5645: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5646:                }
1.620     albertel 5647:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5648:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5649: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5650:                        &log($env{'user.domain'},$env{'user.name'},
                   5651:                             $env{'user.home'},
1.57      www      5652:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5653:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5654:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5655: 		       return '';
                   5656:                    }
                   5657:                }
1.620     albertel 5658:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5659:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5660: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5661:                        &log($env{'user.domain'},$env{'user.name'},
                   5662:                             $env{'user.home'},
1.57      www      5663:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5664:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5665:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5666: 		       return '';
                   5667:                    }
                   5668:                }
                   5669: 	   }
1.29      www      5670:        }
1.52      www      5671:     }
                   5672:    
                   5673: #
                   5674: # Rest of the restrictions depend on selected course
                   5675: #
                   5676: 
1.620     albertel 5677:     unless ($env{'request.course.id'}) {
1.766     albertel 5678: 	if ($thisallowed eq 'A') {
                   5679: 	    return 'A';
1.814     raeburn  5680:         } elsif ($thisallowed eq 'B') {
                   5681:             return 'B';
1.766     albertel 5682: 	} else {
                   5683: 	    return '1';
                   5684: 	}
1.52      www      5685:     }
1.29      www      5686: 
1.52      www      5687: #
                   5688: # Now user is definitely in a course
                   5689: #
1.53      www      5690: 
                   5691: 
                   5692: # Course preferences
                   5693: 
                   5694:    if ($thisallowed=~/C/) {
1.620     albertel 5695:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5696:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5697:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5698: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5699: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5700: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5701: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5702: 			$env{'request.course.id'});
                   5703: 	   }
1.237     www      5704:            return '';
                   5705:        }
                   5706: 
1.620     albertel 5707:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5708: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5709: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5710: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5711: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5712: 			$env{'request.course.id'});
                   5713: 	   }
1.54      www      5714:            return '';
                   5715:        }
1.53      www      5716:    }
                   5717: 
                   5718: # Resource preferences
                   5719: 
                   5720:    if ($thisallowed=~/R/) {
1.620     albertel 5721:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5722:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5723: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5724: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5725: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5726: 	   }
                   5727: 	   return '';
1.54      www      5728:        }
1.53      www      5729:    }
1.30      www      5730: 
1.246     www      5731: # Restricted by state or randomout?
1.30      www      5732: 
1.52      www      5733:    if ($thisallowed=~/X/) {
1.620     albertel 5734:       if ($env{'acc.randomout'}) {
1.579     albertel 5735: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5736:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5737:             return ''; 
                   5738:          }
1.247     www      5739:       }
                   5740:       if (&condval($statecond)) {
1.52      www      5741: 	 return '2';
                   5742:       } else {
                   5743:          return '';
                   5744:       }
                   5745:    }
1.30      www      5746: 
1.766     albertel 5747:     if ($thisallowed eq 'A') {
                   5748: 	return 'A';
1.814     raeburn  5749:     } elsif ($thisallowed eq 'B') {
                   5750:         return 'B';
1.766     albertel 5751:     }
1.52      www      5752:    return 'F';
1.232     www      5753: }
                   5754: 
1.710     albertel 5755: sub split_uri_for_cond {
                   5756:     my $uri=&deversion(&declutter(shift));
                   5757:     my @uriparts=split(/\//,$uri);
                   5758:     my $filename=pop(@uriparts);
                   5759:     my $pathname=join('/',@uriparts);
                   5760:     return ($pathname,$filename);
                   5761: }
1.232     www      5762: # --------------------------------------------------- Is a resource on the map?
                   5763: 
                   5764: sub is_on_map {
1.710     albertel 5765:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5766:     #Trying to find the conditional for the file
1.620     albertel 5767:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5768: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5769:     if ($match) {
1.289     bowersj2 5770: 	return (1,$1);
                   5771:     } else {
1.434     www      5772: 	return (0,0);
1.289     bowersj2 5773:     }
1.12      www      5774: }
                   5775: 
1.427     www      5776: # --------------------------------------------------------- Get symb from alias
                   5777: 
                   5778: sub get_symb_from_alias {
                   5779:     my $symb=shift;
                   5780:     my ($map,$resid,$url)=&decode_symb($symb);
                   5781: # Already is a symb
                   5782:     if ($url) { return $symb; }
                   5783: # Must be an alias
                   5784:     my $aliassymb='';
                   5785:     my %bighash;
1.620     albertel 5786:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5787:                             &GDBM_READER(),0640)) {
                   5788:         my $rid=$bighash{'mapalias_'.$symb};
                   5789: 	if ($rid) {
                   5790: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5791: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5792: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5793: 	}
                   5794:         untie %bighash;
                   5795:     }
                   5796:     return $aliassymb;
                   5797: }
                   5798: 
1.12      www      5799: # ----------------------------------------------------------------- Define Role
                   5800: 
                   5801: sub definerole {
                   5802:   if (allowed('mcr','/')) {
                   5803:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5804:     foreach my $role (split(':',$sysrole)) {
                   5805: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5806:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5807:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5808: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5809:                return "refused:s:$crole&$cqual"; 
                   5810:             }
                   5811:         }
1.191     harris41 5812:     }
1.800     albertel 5813:     foreach my $role (split(':',$domrole)) {
                   5814: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5815:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5816:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5817: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5818:                return "refused:d:$crole&$cqual"; 
                   5819:             }
                   5820:         }
1.191     harris41 5821:     }
1.800     albertel 5822:     foreach my $role (split(':',$courole)) {
                   5823: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5824:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5825:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5826: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5827:                return "refused:c:$crole&$cqual"; 
                   5828:             }
                   5829:         }
1.191     harris41 5830:     }
1.620     albertel 5831:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5832:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5833: 	        "rolesdef_$rolename=".
                   5834:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5835:     return reply($command,$env{'user.home'});
1.12      www      5836:   } else {
                   5837:     return 'refused';
                   5838:   }
1.105     harris41 5839: }
                   5840: 
                   5841: # ---------------- Make a metadata query against the network of library servers
                   5842: 
                   5843: sub metadata_query {
1.244     matthew  5844:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5845:     my %rhash;
1.845     albertel 5846:     my %libserv = &all_library();
1.244     matthew  5847:     my @server_list = (defined($server_array) ? @$server_array
                   5848:                                               : keys(%libserv) );
                   5849:     for my $server (@server_list) {
1.118     harris41 5850: 	unless ($custom or $customshow) {
                   5851: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5852: 	    $rhash{$server}=$reply;
                   5853: 	}
                   5854: 	else {
                   5855: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5856: 			     &escape($custom).':'.&escape($customshow),
                   5857: 			     $server);
                   5858: 	    $rhash{$server}=$reply;
                   5859: 	}
1.112     harris41 5860:     }
1.118     harris41 5861:     return \%rhash;
1.240     www      5862: }
                   5863: 
                   5864: # ----------------------------------------- Send log queries and wait for reply
                   5865: 
                   5866: sub log_query {
                   5867:     my ($uname,$udom,$query,%filters)=@_;
                   5868:     my $uhome=&homeserver($uname,$udom);
                   5869:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5870:     my $uhost=&hostname($uhome);
1.800     albertel 5871:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5872:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5873:                        $uhome);
1.479     albertel 5874:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5875:     return get_query_reply($queryid);
                   5876: }
                   5877: 
1.818     raeburn  5878: # -------------------------- Update MySQL table for portfolio file
                   5879: 
                   5880: sub update_portfolio_table {
1.821     raeburn  5881:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5882:     if ($group ne '') {
                   5883:         $file_name =~s /^\Q$group\E//;
                   5884:     }
1.818     raeburn  5885:     my $homeserver = &homeserver($uname,$udom);
                   5886:     my $queryid=
1.821     raeburn  5887:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5888:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5889:     my $reply = &get_query_reply($queryid);
                   5890:     return $reply;
                   5891: }
                   5892: 
1.899     raeburn  5893: # -------------------------- Update MySQL allusers table
                   5894: 
                   5895: sub update_allusers_table {
                   5896:     my ($uname,$udom,$names) = @_;
                   5897:     my $homeserver = &homeserver($uname,$udom);
                   5898:     my $queryid=
                   5899:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5900:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5901:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5902:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5903:                'generation='.&escape($names->{'generation'}).'%%'.
                   5904:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5905:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5906:     return;
1.899     raeburn  5907: }
                   5908: 
1.508     raeburn  5909: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5910: 
                   5911: sub fetch_enrollment_query {
1.511     raeburn  5912:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5913:     my $homeserver;
1.547     raeburn  5914:     my $maxtries = 1;
1.508     raeburn  5915:     if ($context eq 'automated') {
                   5916:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5917:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5918:     } else {
                   5919:         $homeserver = &homeserver($cnum,$dom);
                   5920:     }
1.838     albertel 5921:     my $host=&hostname($homeserver);
1.506     raeburn  5922:     my $cmd = '';
1.1000    raeburn  5923:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5924:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5925:     }
                   5926:     $cmd =~ s/%%$//;
                   5927:     $cmd = &escape($cmd);
                   5928:     my $query = 'fetchenrollment';
1.620     albertel 5929:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5930:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5931:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5932:         return 'error: '.$queryid;
                   5933:     }
1.506     raeburn  5934:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5935:     my $tries = 1;
                   5936:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5937:         $reply = &get_query_reply($queryid);
                   5938:         $tries ++;
                   5939:     }
1.526     raeburn  5940:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5941:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5942:     } else {
1.901     albertel 5943:         my @responses = split(/:/,$reply);
1.515     raeburn  5944:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5945:             foreach my $line (@responses) {
                   5946:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5947:                 $$replyref{$key} = $value;
                   5948:             }
                   5949:         } else {
1.506     raeburn  5950:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5951:             foreach my $line (@responses) {
                   5952:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5953:                 $$replyref{$key} = $value;
                   5954:                 if ($value > 0) {
1.800     albertel 5955:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5956:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5957:                         my $destname = $pathname.'/'.$filename;
                   5958:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5959:                         if ($xml_classlist =~ /^error/) {
                   5960:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5961:                         } else {
1.506     raeburn  5962:                             if ( open(FILE,">$destname") ) {
                   5963:                                 print FILE &unescape($xml_classlist);
                   5964:                                 close(FILE);
1.526     raeburn  5965:                             } else {
                   5966:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5967:                             }
                   5968:                         }
                   5969:                     }
                   5970:                 }
                   5971:             }
                   5972:         }
                   5973:         return 'ok';
                   5974:     }
                   5975:     return 'error';
                   5976: }
                   5977: 
1.242     www      5978: sub get_query_reply {
                   5979:     my $queryid=shift;
1.240     www      5980:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5981:     my $reply='';
                   5982:     for (1..100) {
                   5983: 	sleep 2;
                   5984:         if (-e $replyfile.'.end') {
1.448     albertel 5985: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5986: 		$reply = join('',<$fh>);
                   5987: 		close($fh);
1.240     www      5988: 	   } else { return 'error: reply_file_error'; }
1.242     www      5989:            return &unescape($reply);
                   5990: 	}
1.240     www      5991:     }
1.242     www      5992:     return 'timeout:'.$queryid;
1.240     www      5993: }
                   5994: 
                   5995: sub courselog_query {
1.241     www      5996: #
                   5997: # possible filters:
                   5998: # url: url or symb
                   5999: # username
                   6000: # domain
                   6001: # action: view, submit, grade
                   6002: # start: timestamp
                   6003: # end: timestamp
                   6004: #
1.240     www      6005:     my (%filters)=@_;
1.620     albertel 6006:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6007:     if ($filters{'url'}) {
                   6008: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6009:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6010:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6011:     }
1.620     albertel 6012:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6013:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6014:     return &log_query($cname,$cdom,'courselog',%filters);
                   6015: }
                   6016: 
                   6017: sub userlog_query {
1.858     raeburn  6018: #
                   6019: # possible filters:
                   6020: # action: log check role
                   6021: # start: timestamp
                   6022: # end: timestamp
                   6023: #
1.240     www      6024:     my ($uname,$udom,%filters)=@_;
                   6025:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6026: }
                   6027: 
1.506     raeburn  6028: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6029: 
                   6030: sub auto_run {
1.508     raeburn  6031:     my ($cnum,$cdom) = @_;
1.876     raeburn  6032:     my $response = 0;
                   6033:     my $settings;
                   6034:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6035:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6036:         $settings = $domconfig{'autoenroll'};
                   6037:         if ($settings->{'run'} eq '1') {
                   6038:             $response = 1;
                   6039:         }
                   6040:     } else {
1.934     raeburn  6041:         my $homeserver;
                   6042:         if (&is_course($cdom,$cnum)) {
                   6043:             $homeserver = &homeserver($cnum,$cdom);
                   6044:         } else {
                   6045:             $homeserver = &domain($cdom,'primary');
                   6046:         }
                   6047:         if ($homeserver ne 'no_host') {
                   6048:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6049:         }
1.876     raeburn  6050:     }
1.506     raeburn  6051:     return $response;
                   6052: }
1.776     albertel 6053: 
1.506     raeburn  6054: sub auto_get_sections {
1.508     raeburn  6055:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6056:     my $homeserver;
                   6057:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6058:         $homeserver = &homeserver($cnum,$cdom);
                   6059:     }
                   6060:     if (!defined($homeserver)) { 
                   6061:         if ($cdom =~ /^$match_domain$/) {
                   6062:             $homeserver = &domain($cdom,'primary');
                   6063:         }
                   6064:     }
                   6065:     my @secs;
                   6066:     if (defined($homeserver)) {
                   6067:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6068:         unless ($response eq 'refused') {
                   6069:             @secs = split(/:/,$response);
                   6070:         }
1.506     raeburn  6071:     }
                   6072:     return @secs;
                   6073: }
1.776     albertel 6074: 
1.506     raeburn  6075: sub auto_new_course {
1.1099    raeburn  6076:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6077:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6078:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6079:     return $response;
                   6080: }
1.776     albertel 6081: 
1.506     raeburn  6082: sub auto_validate_courseID {
1.508     raeburn  6083:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6084:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6085:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6086:     return $response;
                   6087: }
1.776     albertel 6088: 
1.1007    raeburn  6089: sub auto_validate_instcode {
1.1020    raeburn  6090:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6091:     my ($homeserver,$response);
                   6092:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6093:         $homeserver = &homeserver($cnum,$cdom);
                   6094:     }
                   6095:     if (!defined($homeserver)) {
                   6096:         if ($cdom =~ /^$match_domain$/) {
                   6097:             $homeserver = &domain($cdom,'primary');
                   6098:         }
                   6099:     }
1.1065    raeburn  6100:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6101:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6102:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6103:     return ($outcome,$description);
1.1007    raeburn  6104: }
                   6105: 
1.506     raeburn  6106: sub auto_create_password {
1.873     raeburn  6107:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6108:     my ($homeserver,$response);
1.506     raeburn  6109:     my $create_passwd = 0;
                   6110:     my $authchk = '';
1.873     raeburn  6111:     if ($udom =~ /^$match_domain$/) {
                   6112:         $homeserver = &domain($udom,'primary');
                   6113:     }
                   6114:     if ($homeserver eq '') {
                   6115:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6116:             $homeserver = &homeserver($cnum,$cdom);
                   6117:         }
                   6118:     }
                   6119:     if ($homeserver eq '') {
                   6120:         $authchk = 'nodomain';
1.506     raeburn  6121:     } else {
1.873     raeburn  6122:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6123:         if ($response eq 'refused') {
                   6124:             $authchk = 'refused';
                   6125:         } else {
1.901     albertel 6126:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6127:         }
1.506     raeburn  6128:     }
                   6129:     return ($authparam,$create_passwd,$authchk);
                   6130: }
                   6131: 
1.706     raeburn  6132: sub auto_photo_permission {
                   6133:     my ($cnum,$cdom,$students) = @_;
                   6134:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6135:     my ($outcome,$perm_reqd,$conditions) = 
                   6136: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6137:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6138: 	return (undef,undef);
                   6139:     }
1.706     raeburn  6140:     return ($outcome,$perm_reqd,$conditions);
                   6141: }
                   6142: 
                   6143: sub auto_checkphotos {
                   6144:     my ($uname,$udom,$pid) = @_;
                   6145:     my $homeserver = &homeserver($uname,$udom);
                   6146:     my ($result,$resulttype);
                   6147:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6148: 				   &escape($uname).':'.&escape($pid),
                   6149: 				   $homeserver));
1.709     albertel 6150:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6151: 	return (undef,undef);
                   6152:     }
1.706     raeburn  6153:     if ($outcome) {
                   6154:         ($result,$resulttype) = split(/:/,$outcome);
                   6155:     } 
                   6156:     return ($result,$resulttype);
                   6157: }
                   6158: 
                   6159: sub auto_photochoice {
                   6160:     my ($cnum,$cdom) = @_;
                   6161:     my $homeserver = &homeserver($cnum,$cdom);
                   6162:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6163: 						       &escape($cdom),
                   6164: 						       $homeserver)));
1.709     albertel 6165:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6166: 	return (undef,undef);
                   6167:     }
1.706     raeburn  6168:     return ($update,$comment);
                   6169: }
                   6170: 
                   6171: sub auto_photoupdate {
                   6172:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6173:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6174:     my $host=&hostname($homeserver);
1.706     raeburn  6175:     my $cmd = '';
                   6176:     my $maxtries = 1;
1.800     albertel 6177:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6178:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6179:     }
                   6180:     $cmd =~ s/%%$//;
                   6181:     $cmd = &escape($cmd);
                   6182:     my $query = 'institutionalphotos';
                   6183:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6184:     unless ($queryid=~/^\Q$host\E\_/) {
                   6185:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6186:         return 'error: '.$queryid;
                   6187:     }
                   6188:     my $reply = &get_query_reply($queryid);
                   6189:     my $tries = 1;
                   6190:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6191:         $reply = &get_query_reply($queryid);
                   6192:         $tries ++;
                   6193:     }
                   6194:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6195:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6196:     } else {
                   6197:         my @responses = split(/:/,$reply);
                   6198:         my $outcome = shift(@responses); 
                   6199:         foreach my $item (@responses) {
                   6200:             my ($key,$value) = split(/=/,$item);
                   6201:             $$photo{$key} = $value;
                   6202:         }
                   6203:         return $outcome;
                   6204:     }
                   6205:     return 'error';
                   6206: }
                   6207: 
1.521     raeburn  6208: sub auto_instcode_format {
1.793     albertel 6209:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6210: 	$cat_order) = @_;
1.521     raeburn  6211:     my $courses = '';
1.772     raeburn  6212:     my @homeservers;
1.521     raeburn  6213:     if ($caller eq 'global') {
1.841     albertel 6214: 	my %servers = &get_servers($codedom,'library');
                   6215: 	foreach my $tryserver (keys(%servers)) {
                   6216: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6217: 		push(@homeservers,$tryserver);
                   6218: 	    }
1.584     raeburn  6219:         }
1.1022    raeburn  6220:     } elsif ($caller eq 'requests') {
                   6221:         if ($codedom =~ /^$match_domain$/) {
                   6222:             my $chome = &domain($codedom,'primary');
                   6223:             unless ($chome eq 'no_host') {
                   6224:                 push(@homeservers,$chome);
                   6225:             }
                   6226:         }
1.521     raeburn  6227:     } else {
1.772     raeburn  6228:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6229:     }
1.793     albertel 6230:     foreach my $code (keys(%{$instcodes})) {
                   6231:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6232:     }
                   6233:     chop($courses);
1.772     raeburn  6234:     my $ok_response = 0;
                   6235:     my $response;
                   6236:     while (@homeservers > 0 && $ok_response == 0) {
                   6237:         my $server = shift(@homeservers); 
                   6238:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6239:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6240:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6241: 		split(/:/,$response);
1.772     raeburn  6242:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6243:             push(@{$codetitles},&str2array($codetitles_str));
                   6244:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6245:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6246:             $ok_response = 1;
                   6247:         }
                   6248:     }
                   6249:     if ($ok_response) {
1.521     raeburn  6250:         return 'ok';
1.772     raeburn  6251:     } else {
                   6252:         return $response;
1.521     raeburn  6253:     }
                   6254: }
                   6255: 
1.792     raeburn  6256: sub auto_instcode_defaults {
                   6257:     my ($domain,$returnhash,$code_order) = @_;
                   6258:     my @homeservers;
1.841     albertel 6259: 
                   6260:     my %servers = &get_servers($domain,'library');
                   6261:     foreach my $tryserver (keys(%servers)) {
                   6262: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6263: 	    push(@homeservers,$tryserver);
                   6264: 	}
1.792     raeburn  6265:     }
1.841     albertel 6266: 
1.792     raeburn  6267:     my $response;
1.841     albertel 6268:     foreach my $server (@homeservers) {
1.792     raeburn  6269:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6270:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6271: 	
                   6272: 	foreach my $pair (split(/\&/,$response)) {
                   6273: 	    my ($name,$value)=split(/\=/,$pair);
                   6274: 	    if ($name eq 'code_order') {
                   6275: 		@{$code_order} = split(/\&/,&unescape($value));
                   6276: 	    } else {
                   6277: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6278: 	    }
                   6279: 	}
                   6280: 	return 'ok';
1.792     raeburn  6281:     }
1.841     albertel 6282: 
                   6283:     return $response;
1.1003    raeburn  6284: }
                   6285: 
                   6286: sub auto_possible_instcodes {
1.1007    raeburn  6287:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6288:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6289:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6290:         return;
                   6291:     }
1.1003    raeburn  6292:     my (@homeservers,$uhome);
                   6293:     if (defined(&domain($domain,'primary'))) {
                   6294:         $uhome=&domain($domain,'primary');
                   6295:         push(@homeservers,&domain($domain,'primary'));
                   6296:     } else {
                   6297:         my %servers = &get_servers($domain,'library');
                   6298:         foreach my $tryserver (keys(%servers)) {
                   6299:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6300:                 push(@homeservers,$tryserver);
                   6301:             }
                   6302:         }
                   6303:     }
                   6304:     my $response;
                   6305:     foreach my $server (@homeservers) {
                   6306:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6307:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6308:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6309:             split(':',$response);
                   6310:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6311:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6312:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6313:             my ($name,$value)=split('=',$item);
                   6314:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6315:         }
                   6316:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6317:             my ($name,$value)=split('=',$item);
                   6318:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6319:         }
                   6320:         return 'ok';
                   6321:     }
                   6322:     return $response;
                   6323: }
1.792     raeburn  6324: 
1.1010    raeburn  6325: sub auto_courserequest_checks {
                   6326:     my ($dom) = @_;
1.1020    raeburn  6327:     my ($homeserver,%validations);
                   6328:     if ($dom =~ /^$match_domain$/) {
                   6329:         $homeserver = &domain($dom,'primary');
                   6330:     }
                   6331:     unless ($homeserver eq 'no_host') {
                   6332:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6333:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6334:             my @items = split(/&/,$response);
                   6335:             foreach my $item (@items) {
                   6336:                 my ($key,$value) = split('=',$item);
                   6337:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6338:             }
                   6339:         }
                   6340:     }
1.1010    raeburn  6341:     return %validations; 
                   6342: }
                   6343: 
1.1020    raeburn  6344: sub auto_courserequest_validation {
                   6345:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6346:     my ($homeserver,$response);
                   6347:     if ($dom =~ /^$match_domain$/) {
                   6348:         $homeserver = &domain($dom,'primary');
                   6349:     }
                   6350:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6351:           
1.1020    raeburn  6352:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6353:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6354:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6355:                                     $homeserver));
                   6356:     }
                   6357:     return $response;
                   6358: }
                   6359: 
1.777     albertel 6360: sub auto_validate_class_sec {
1.918     raeburn  6361:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6362:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6363:     my $ownerlist;
                   6364:     if (ref($owners) eq 'ARRAY') {
                   6365:         $ownerlist = join(',',@{$owners});
                   6366:     } else {
                   6367:         $ownerlist = $owners;
                   6368:     }
1.773     raeburn  6369:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6370:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6371:     return $response;
                   6372: }
                   6373: 
1.679     raeburn  6374: # ------------------------------------------------------- Course Group routines
                   6375: 
                   6376: sub get_coursegroups {
1.809     raeburn  6377:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6378:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6379: }
                   6380: 
1.679     raeburn  6381: sub modify_coursegroup {
                   6382:     my ($cdom,$cnum,$groupsettings) = @_;
                   6383:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6384: }
                   6385: 
1.809     raeburn  6386: sub toggle_coursegroup_status {
                   6387:     my ($cdom,$cnum,$group,$action) = @_;
                   6388:     my ($from_namespace,$to_namespace);
                   6389:     if ($action eq 'delete') {
                   6390:         $from_namespace = 'coursegroups';
                   6391:         $to_namespace = 'deleted_groups';
                   6392:     } else {
                   6393:         $from_namespace = 'deleted_groups';
                   6394:         $to_namespace = 'coursegroups';
                   6395:     }
                   6396:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6397:     if (my $tmp = &error(%curr_group)) {
                   6398:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6399:         return ('read error',$tmp);
                   6400:     } else {
                   6401:         my %savedsettings = %curr_group; 
1.809     raeburn  6402:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6403:         my $deloutcome;
                   6404:         if ($result eq 'ok') {
1.809     raeburn  6405:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6406:         } else {
                   6407:             return ('write error',$result);
                   6408:         }
                   6409:         if ($deloutcome eq 'ok') {
                   6410:             return 'ok';
                   6411:         } else {
                   6412:             return ('delete error',$deloutcome);
                   6413:         }
                   6414:     }
                   6415: }
                   6416: 
1.679     raeburn  6417: sub modify_group_roles {
1.957     raeburn  6418:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6419:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6420:     my $role = 'gr/'.&escape($userprivs);
                   6421:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6422:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6423:     if ($result eq 'ok') {
                   6424:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6425:     }
1.679     raeburn  6426:     return $result;
                   6427: }
                   6428: 
                   6429: sub modify_coursegroup_membership {
                   6430:     my ($cdom,$cnum,$membership) = @_;
                   6431:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6432:     return $result;
                   6433: }
                   6434: 
1.682     raeburn  6435: sub get_active_groups {
                   6436:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6437:     my $now = time;
                   6438:     my %groups = ();
                   6439:     foreach my $key (keys(%env)) {
1.811     albertel 6440:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6441:             my ($start,$end) = split(/\./,$env{$key});
                   6442:             if (($end!=0) && ($end<$now)) { next; }
                   6443:             if (($start!=0) && ($start>$now)) { next; }
                   6444:             if ($1 eq $cdom && $2 eq $cnum) {
                   6445:                 $groups{$3} = $env{$key} ;
                   6446:             }
                   6447:         }
                   6448:     }
                   6449:     return %groups;
                   6450: }
                   6451: 
1.683     raeburn  6452: sub get_group_membership {
                   6453:     my ($cdom,$cnum,$group) = @_;
                   6454:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6455: }
                   6456: 
                   6457: sub get_users_groups {
                   6458:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6459:     my @usersgroups;
1.683     raeburn  6460:     my $cachetime=1800;
                   6461: 
                   6462:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6463:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6464:     if (defined($cached)) {
1.734     albertel 6465:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6466:     } else {  
                   6467:         $grouplist = '';
1.816     raeburn  6468:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6469:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6470:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6471:         my $access_end = $env{'course.'.$courseid.
                   6472:                               '.default_enrollment_end_date'};
                   6473:         my $now = time;
                   6474:         foreach my $key (keys(%roleshash)) {
                   6475:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6476:                 my $group = $1;
                   6477:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6478:                     my $start = $2;
                   6479:                     my $end = $1;
                   6480:                     if ($start == -1) { next; } # deleted from group
                   6481:                     if (($start!=0) && ($start>$now)) { next; }
                   6482:                     if (($end!=0) && ($end<$now)) {
                   6483:                         if ($access_end && $access_end < $now) {
                   6484:                             if ($access_end - $end < 86400) {
                   6485:                                 push(@usersgroups,$group);
1.733     raeburn  6486:                             }
                   6487:                         }
1.817     raeburn  6488:                         next;
1.733     raeburn  6489:                     }
1.817     raeburn  6490:                     push(@usersgroups,$group);
1.683     raeburn  6491:                 }
                   6492:             }
                   6493:         }
1.817     raeburn  6494:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6495:         $grouplist = join(':',@usersgroups);
                   6496:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6497:     }
1.733     raeburn  6498:     return @usersgroups;
1.683     raeburn  6499: }
                   6500: 
                   6501: sub devalidate_getgroups_cache {
                   6502:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6503:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6504: 
1.683     raeburn  6505:     my $hashid="$udom:$uname:$courseid";
                   6506:     &devalidate_cache_new('getgroups',$hashid);
                   6507: }
                   6508: 
1.12      www      6509: # ------------------------------------------------------------------ Plain Text
                   6510: 
                   6511: sub plaintext {
1.988     raeburn  6512:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6513:     if ($short =~ m{^cr/}) {
1.758     albertel 6514: 	return (split('/',$short))[-1];
                   6515:     }
1.742     raeburn  6516:     if (!defined($cid)) {
                   6517:         $cid = $env{'request.course.id'};
                   6518:     }
                   6519:     my %rolenames = (
1.1008    raeburn  6520:                       Course    => 'std',
                   6521:                       Community => 'alt1',
1.742     raeburn  6522:                     );
1.1037    raeburn  6523:     if ($cid ne '') {
                   6524:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6525:             unless ($forcedefault) {
                   6526:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6527:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6528:                 return &Apache::lonlocal::mt($roletext);
                   6529:             }
                   6530:         }
                   6531:     }
                   6532:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6533:         (defined($rolenames{$type})) && 
                   6534:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6535:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6536:     } elsif ($cid ne '') {
                   6537:         my $crstype = $env{'course.'.$cid.'.type'};
                   6538:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6539:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6540:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6541:         }
1.742     raeburn  6542:     }
1.1037    raeburn  6543:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6544: }
                   6545: 
                   6546: # ----------------------------------------------------------------- Assign Role
                   6547: 
                   6548: sub assignrole {
1.957     raeburn  6549:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6550:         $context)=@_;
1.21      www      6551:     my $mrole;
                   6552:     if ($role =~ /^cr\//) {
1.393     www      6553:         my $cwosec=$url;
1.811     albertel 6554:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6555: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6556:            my $refused = 1;
                   6557:            if ($context eq 'requestcourses') {
                   6558:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6559:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6560:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6561:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6562:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6563:                            if ($crsenv{'internal.courseowner'} eq
                   6564:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6565:                                $refused = '';
                   6566:                            }
                   6567:                        }
                   6568:                    }
                   6569:                }
                   6570:            }
                   6571:            if ($refused) {
                   6572:                &logthis('Refused custom assignrole: '.
                   6573:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6574:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6575:                return 'refused';
                   6576:            }
1.104     www      6577:         }
1.21      www      6578:         $mrole='cr';
1.678     raeburn  6579:     } elsif ($role =~ /^gr\//) {
                   6580:         my $cwogrp=$url;
1.811     albertel 6581:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6582:         unless (&allowed('mdg',$cwogrp)) {
                   6583:             &logthis('Refused group assignrole: '.
                   6584:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6585:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6586:             return 'refused';
                   6587:         }
                   6588:         $mrole='gr';
1.21      www      6589:     } else {
1.82      www      6590:         my $cwosec=$url;
1.811     albertel 6591:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6592:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6593:             my $refused;
                   6594:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6595:                 if (!(&allowed('c'.$role,$url))) {
                   6596:                     $refused = 1;
                   6597:                 }
                   6598:             } else {
                   6599:                 $refused = 1;
                   6600:             }
1.947     raeburn  6601:             if ($refused) {
1.1045    raeburn  6602:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6603:                 if (!$selfenroll && $context eq 'course') {
                   6604:                     my %crsenv;
                   6605:                     if ($role eq 'cc' || $role eq 'co') {
                   6606:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6607:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6608:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6609:                                 if ($crsenv{'internal.courseowner'} eq 
                   6610:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6611:                                     $refused = '';
                   6612:                                 }
                   6613:                             }
                   6614:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6615:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6616:                                 if ($crsenv{'internal.courseowner'} eq 
                   6617:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6618:                                     $refused = '';
                   6619:                                 }
                   6620:                             }
                   6621:                         }
                   6622:                     }
                   6623:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6624:                     $refused = '';
1.1017    raeburn  6625:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6626:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6627:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6628:                         my $wrongcc;
                   6629:                         if ($cnum =~ /^$match_community$/) {
                   6630:                             $wrongcc = 1 if ($role eq 'cc');
                   6631:                         } else {
                   6632:                             $wrongcc = 1 if ($role eq 'co');
                   6633:                         }
                   6634:                         unless ($wrongcc) {
                   6635:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6636:                             if ($crsenv{'internal.courseowner'} eq 
                   6637:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6638:                                 $refused = '';
                   6639:                             }
1.1017    raeburn  6640:                         }
                   6641:                     }
                   6642:                 }
                   6643:                 if ($refused) {
1.947     raeburn  6644:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6645:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6646: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6647:                     return 'refused';
                   6648:                 }
1.932     raeburn  6649:             }
1.104     www      6650:         }
1.21      www      6651:         $mrole=$role;
                   6652:     }
1.620     albertel 6653:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6654:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6655:     if ($end) { $command.='_'.$end; }
1.21      www      6656:     if ($start) {
                   6657: 	if ($end) { 
1.81      www      6658:            $command.='_'.$start; 
1.21      www      6659:         } else {
1.81      www      6660:            $command.='_0_'.$start;
1.21      www      6661:         }
                   6662:     }
1.739     raeburn  6663:     my $origstart = $start;
                   6664:     my $origend = $end;
1.957     raeburn  6665:     my $delflag;
1.357     www      6666: # actually delete
                   6667:     if ($deleteflag) {
1.373     www      6668: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6669: # modify command to delete the role
1.620     albertel 6670:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6671:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6672: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6673: # set start and finish to negative values for userrolelog
                   6674:            $start=-1;
                   6675:            $end=-1;
1.957     raeburn  6676:            $delflag = 1;
1.357     www      6677:         }
                   6678:     }
                   6679: # send command
1.349     www      6680:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6681: # log new user role if status is ok
1.349     www      6682:     if ($answer eq 'ok') {
1.663     raeburn  6683: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6684: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6685:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6686:         unless ($role =~ /^gr/) {
                   6687:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6688:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6689:         }
1.1053    raeburn  6690:         if ($role eq 'cc') {
                   6691:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6692:         }
1.349     www      6693:     }
                   6694:     return $answer;
1.169     harris41 6695: }
                   6696: 
1.1053    raeburn  6697: sub autoupdate_coowners {
                   6698:     my ($url,$end,$start,$uname,$udom) = @_;
                   6699:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6700:     if (($cdom ne '') && ($cnum ne '')) {
                   6701:         my $now = time;
                   6702:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6703:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6704:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6705:             my $instcode = $coursehash{'internal.coursecode'};
                   6706:             if ($instcode ne '') {
1.1056    raeburn  6707:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6708:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6709:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6710:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6711:                         if ($result eq 'valid') {
                   6712:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6713:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6714:                                     push(@newcoowners,$coowner);
                   6715:                                 }
                   6716:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6717:                                     push(@newcoowners,$uname.':'.$udom);
                   6718:                                 }
                   6719:                                 @newcoowners = sort(@newcoowners);
                   6720:                             } else {
                   6721:                                 push(@newcoowners,$uname.':'.$udom);
                   6722:                             }
                   6723:                         } else {
                   6724:                             if ($coursehash{'internal.co-owners'}) {
                   6725:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6726:                                     unless ($coowner eq $uname.':'.$udom) {
                   6727:                                         push(@newcoowners,$coowner);
                   6728:                                     }
                   6729:                                 }
                   6730:                                 unless (@newcoowners > 0) {
                   6731:                                     $delcoowners = 1;
                   6732:                                     $coowners = '';
                   6733:                                 }
                   6734:                             }
                   6735:                         }
                   6736:                         if (@newcoowners || $delcoowners) {
                   6737:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6738:                                             $delcoowners,@newcoowners);
                   6739:                         }
                   6740:                     }
                   6741:                 }
                   6742:             }
                   6743:         }
                   6744:     }
                   6745: }
                   6746: 
                   6747: sub store_coowners {
                   6748:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6749:     my $cid = $cdom.'_'.$cnum;
                   6750:     my ($coowners,$delresult,$putresult);
                   6751:     if (@newcoowners) {
                   6752:         $coowners = join(',',@newcoowners);
                   6753:         my %coownershash = (
                   6754:                             'internal.co-owners' => $coowners,
                   6755:                            );
                   6756:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6757:         if ($putresult eq 'ok') {
                   6758:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6759:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6760:             }
                   6761:         }
                   6762:     }
                   6763:     if ($delcoowners) {
                   6764:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6765:         if ($delresult eq 'ok') {
                   6766:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6767:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6768:             }
                   6769:         }
                   6770:     }
                   6771:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6772:         my %crsinfo =
                   6773:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6774:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6775:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6776:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6777:         }
                   6778:     }
                   6779: }
                   6780: 
1.169     harris41 6781: # -------------------------------------------------- Modify user authentication
1.197     www      6782: # Overrides without validation
                   6783: 
1.169     harris41 6784: sub modifyuserauth {
                   6785:     my ($udom,$uname,$umode,$upass)=@_;
                   6786:     my $uhome=&homeserver($uname,$udom);
1.197     www      6787:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6788:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6789:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6790:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6791:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6792: 		     &escape($upass),$uhome);
1.620     albertel 6793:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6794:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6795:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6796:     &log($udom,,$uname,$uhome,
1.620     albertel 6797:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6798:                                      $env{'user.name'}.', '.$umode.
1.197     www      6799:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6800:     unless ($reply eq 'ok') {
1.197     www      6801:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6802: 	return 'error: '.$reply;
                   6803:     }   
1.170     harris41 6804:     return 'ok';
1.80      www      6805: }
                   6806: 
1.81      www      6807: # --------------------------------------------------------------- Modify a user
1.80      www      6808: 
1.81      www      6809: sub modifyuser {
1.206     matthew  6810:     my ($udom,    $uname, $uid,
                   6811:         $umode,   $upass, $first,
                   6812:         $middle,  $last,  $gene,
1.1058    raeburn  6813:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6814:     $udom= &LONCAPA::clean_domain($udom);
                   6815:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6816:     my $showcandelete = 'none';
                   6817:     if (ref($candelete) eq 'ARRAY') {
                   6818:         if (@{$candelete} > 0) {
                   6819:             $showcandelete = join(', ',@{$candelete});
                   6820:         }
                   6821:     }
1.81      www      6822:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6823:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6824: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6825:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6826:                                      ' desiredhome not specified'). 
1.620     albertel 6827:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6828:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6829:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6830:     my $newuser;
                   6831:     if ($uhome eq 'no_host') {
                   6832:         $newuser = 1;
                   6833:     }
1.80      www      6834: # ----------------------------------------------------------------- Create User
1.406     albertel 6835:     if (($uhome eq 'no_host') && 
                   6836: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6837:         my $unhome='';
1.844     albertel 6838:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6839:             $unhome = $desiredhome;
1.620     albertel 6840: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6841: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6842:         } else { # load balancing routine for determining $unhome
1.81      www      6843:             my $loadm=10000000;
1.841     albertel 6844: 	    my %servers = &get_servers($udom,'library');
                   6845: 	    foreach my $tryserver (keys(%servers)) {
                   6846: 		my $answer=reply('load',$tryserver);
                   6847: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6848: 		    $loadm=$answer;
                   6849: 		    $unhome=$tryserver;
                   6850: 		}
1.80      www      6851: 	    }
                   6852:         }
                   6853:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6854: 	    return 'error: unable to find a home server for '.$uname.
                   6855:                    ' in domain '.$udom;
1.80      www      6856:         }
                   6857:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6858:                          &escape($upass),$unhome);
                   6859: 	unless ($reply eq 'ok') {
                   6860:             return 'error: '.$reply;
                   6861:         }   
1.230     stredwic 6862:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6863:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6864: 	    return 'error: unable verify users home machine.';
1.80      www      6865:         }
1.209     matthew  6866:     }   # End of creation of new user
1.80      www      6867: # ---------------------------------------------------------------------- Add ID
                   6868:     if ($uid) {
                   6869:        $uid=~tr/A-Z/a-z/;
                   6870:        my %uidhash=&idrget($udom,$uname);
1.196     www      6871:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6872:          && (!$forceid)) {
1.80      www      6873: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6874: 	      return 'error: user id "'.$uid.'" does not match '.
                   6875:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6876:           }
                   6877:        } else {
                   6878: 	  &idput($udom,($uname => $uid));
                   6879:        }
                   6880:     }
                   6881: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6882:     my @tmp=&get('environment',
1.899     raeburn  6883: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6884:                     'permanentemail','inststatus'],
1.134     albertel 6885: 		   $udom,$uname);
1.1075    raeburn  6886:     my (%names,%oldnames);
1.313     matthew  6887:     if ($tmp[0] =~ m/^error:.*/) { 
                   6888:         %names=(); 
                   6889:     } else {
                   6890:         %names = @tmp;
1.1075    raeburn  6891:         %oldnames = %names;
1.313     matthew  6892:     }
1.388     www      6893: #
1.1058    raeburn  6894: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6895: # of users did not contain them), do not overwrite existing values
                   6896: # unless field is in $candelete array ref.  
                   6897: #
                   6898: 
                   6899:     my @fields = ('firstname','middlename','lastname','generation',
                   6900:                   'permanentemail','id');
                   6901:     my %newvalues;
                   6902:     if (ref($candelete) eq 'ARRAY') {
                   6903:         foreach my $field (@fields) {
                   6904:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6905:                 if ($field eq 'firstname') {
                   6906:                     $names{$field} = $first;
                   6907:                 } elsif ($field eq 'middlename') {
                   6908:                     $names{$field} = $middle;
                   6909:                 } elsif ($field eq 'lastname') {
                   6910:                     $names{$field} = $last;
                   6911:                 } elsif ($field eq 'generation') { 
                   6912:                     $names{$field} = $gene;
                   6913:                 } elsif ($field eq 'permanentemail') {
                   6914:                     $names{$field} = $email;
                   6915:                 } elsif ($field eq 'id') {
                   6916:                     $names{$field}  = $uid;
                   6917:                 }
                   6918:             }
                   6919:         }
                   6920:     }
1.388     www      6921:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6922:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6923:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6924:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6925:     if ($email) {
                   6926:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6927:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6928:     }
1.899     raeburn  6929:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6930:     if (defined($inststatus)) {
                   6931:         $names{'inststatus'} = '';
                   6932:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6933:         if (ref($usertypes) eq 'HASH') {
                   6934:             my @okstatuses; 
                   6935:             foreach my $item (split(/:/,$inststatus)) {
                   6936:                 if (defined($usertypes->{$item})) {
                   6937:                     push(@okstatuses,$item);  
                   6938:                 }
                   6939:             }
                   6940:             if (@okstatuses) {
                   6941:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6942:             }
                   6943:         }
                   6944:     }
1.1075    raeburn  6945:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6946:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6947:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6948:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6949:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6950:     } else {
                   6951:         $logmsg .= ' during self creation';
                   6952:     }
1.1075    raeburn  6953:     my $changed;
                   6954:     if ($newuser) {
                   6955:         $changed = 1;
                   6956:     } else {
                   6957:         foreach my $field (@fields) {
                   6958:             if ($names{$field} ne $oldnames{$field}) {
                   6959:                 $changed = 1;
                   6960:                 last;
                   6961:             }
                   6962:         }
                   6963:     }
                   6964:     unless ($changed) {
                   6965:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6966:         &logthis($logmsg);
                   6967:         return 'ok';
                   6968:     }
                   6969:     my $reply = &put('environment', \%names, $udom,$uname);
                   6970:     if ($reply ne 'ok') { 
                   6971:         return 'error: '.$reply;
                   6972:     }
1.1087    raeburn  6973:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   6974:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   6975:     }
1.1075    raeburn  6976:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6977:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6978:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6979:     &logthis($logmsg);
1.134     albertel 6980:     return 'ok';
1.80      www      6981: }
                   6982: 
1.81      www      6983: # -------------------------------------------------------------- Modify student
1.80      www      6984: 
1.81      www      6985: sub modifystudent {
                   6986:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6987:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6988:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6989:     if (!$cid) {
1.620     albertel 6990: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6991: 	    return 'not_in_class';
                   6992: 	}
1.80      www      6993:     }
                   6994: # --------------------------------------------------------------- Make the user
1.81      www      6995:     my $reply=&modifyuser
1.209     matthew  6996: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6997:          $desiredhome,$email,$inststatus);
1.80      www      6998:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6999:     # This will cause &modify_student_enrollment to get the uid from the
                   7000:     # students environment
                   7001:     $uid = undef if (!$forceid);
1.455     albertel 7002:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7003: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7004:     return $reply;
                   7005: }
                   7006: 
                   7007: sub modify_student_enrollment {
1.957     raeburn  7008:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7009:     my ($cdom,$cnum,$chome);
                   7010:     if (!$cid) {
1.620     albertel 7011: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7012: 	    return 'not_in_class';
                   7013: 	}
1.620     albertel 7014: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7015: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7016:     } else {
                   7017: 	($cdom,$cnum)=split(/_/,$cid);
                   7018:     }
1.620     albertel 7019:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7020:     if (!$chome) {
1.457     raeburn  7021: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7022:     }
1.455     albertel 7023:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7024:     # Make sure the user exists
1.81      www      7025:     my $uhome=&homeserver($uname,$udom);
                   7026:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7027: 	return 'error: no such user';
                   7028:     }
1.297     matthew  7029:     # Get student data if we were not given enough information
                   7030:     if (!defined($first)  || $first  eq '' || 
                   7031:         !defined($last)   || $last   eq '' || 
                   7032:         !defined($uid)    || $uid    eq '' || 
                   7033:         !defined($middle) || $middle eq '' || 
                   7034:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7035:         # They did not supply us with enough data to enroll the student, so
                   7036:         # we need to pick up more information.
1.297     matthew  7037:         my %tmp = &get('environment',
1.294     matthew  7038:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7039:                        ,$udom,$uname);
                   7040: 
1.800     albertel 7041:         #foreach my $key (keys(%tmp)) {
                   7042:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7043:         #}
1.294     matthew  7044:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7045:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7046:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7047:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7048:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7049:     }
1.556     albertel 7050:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7051:     my $reply=cput('classlist',
                   7052: 		   {"$uname:$udom" => 
1.515     raeburn  7053: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7054: 		   $cdom,$cnum);
1.81      www      7055:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7056: 	return 'error: '.$reply;
1.652     albertel 7057:     } else {
                   7058: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7059:     }
1.297     matthew  7060:     # Add student role to user
1.83      www      7061:     my $uurl='/'.$cid;
1.81      www      7062:     $uurl=~s/\_/\//g;
                   7063:     if ($usec) {
                   7064: 	$uurl.='/'.$usec;
                   7065:     }
1.957     raeburn  7066:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7067: }
                   7068: 
1.556     albertel 7069: sub format_name {
                   7070:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7071:     my $name;
                   7072:     if ($first ne 'lastname') {
                   7073: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7074:     } else {
                   7075: 	if ($lastname=~/\S/) {
                   7076: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7077: 	    $name=~s/\s+,/,/;
                   7078: 	} else {
                   7079: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7080: 	}
                   7081:     }
                   7082:     $name=~s/^\s+//;
                   7083:     $name=~s/\s+$//;
                   7084:     $name=~s/\s+/ /g;
                   7085:     return $name;
                   7086: }
                   7087: 
1.84      www      7088: # ------------------------------------------------- Write to course preferences
                   7089: 
                   7090: sub writecoursepref {
                   7091:     my ($courseid,%prefs)=@_;
                   7092:     $courseid=~s/^\///;
                   7093:     $courseid=~s/\_/\//g;
                   7094:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7095:     my $chome=homeserver($cnum,$cdomain);
                   7096:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7097: 	return 'error: no such course';
                   7098:     }
                   7099:     my $cstring='';
1.800     albertel 7100:     foreach my $pref (keys(%prefs)) {
                   7101: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7102:     }
1.84      www      7103:     $cstring=~s/\&$//;
                   7104:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7105: }
                   7106: 
                   7107: # ---------------------------------------------------------- Make/modify course
                   7108: 
                   7109: sub createcourse {
1.741     raeburn  7110:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7111:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7112:     $url=&declutter($url);
                   7113:     my $cid='';
1.1028    raeburn  7114:     if ($context eq 'requestcourses') {
                   7115:         my $can_create = 0;
                   7116:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7117:         if ($udom eq $ownerdom) {
                   7118:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7119:                                   $context)) {
                   7120:                 $can_create = 1;
                   7121:             }
                   7122:         } else {
                   7123:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7124:                                            $category);
                   7125:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7126:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7127:                 if (@curr > 0) {
                   7128:                     my @options = qw(approval validate autolimit);
                   7129:                     my $optregex = join('|',@options);
                   7130:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7131:                         $can_create = 1;
                   7132:                     }
                   7133:                 }
                   7134:             }
                   7135:         }
                   7136:         if ($can_create) {
                   7137:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7138:                 unless (&allowed('ccc',$udom)) {
                   7139:                     return 'refused'; 
                   7140:                 }
1.1017    raeburn  7141:             }
                   7142:         } else {
                   7143:             return 'refused';
                   7144:         }
1.1028    raeburn  7145:     } elsif (!&allowed('ccc',$udom)) {
                   7146:         return 'refused';
1.84      www      7147:     }
1.1011    raeburn  7148: # --------------------------------------------------------------- Get Unique ID
                   7149:     my $uname;
                   7150:     if ($cnum =~ /^$match_courseid$/) {
                   7151:         my $chome=&homeserver($cnum,$udom,'true');
                   7152:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7153:             $uname = $cnum;
                   7154:         } else {
1.1038    raeburn  7155:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7156:         }
                   7157:     } else {
1.1038    raeburn  7158:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7159:     }
                   7160:     return $uname if ($uname =~ /^error/);
                   7161: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7162:     if (!defined($course_server)) {
                   7163:         if (defined(&domain($udom,'primary'))) {
                   7164:             $course_server = &domain($udom,'primary');
                   7165:         } else {
                   7166:             $course_server = $env{'user.home'}; 
                   7167:         }
                   7168:     }
                   7169:     my %host_servers =
                   7170:         &Apache::lonnet::get_servers($udom,'library');
                   7171:     unless ($host_servers{$course_server}) {
                   7172:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7173:     }
1.84      www      7174: # ------------------------------------------------------------- Make the course
                   7175:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7176:                       $course_server);
1.84      www      7177:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7178:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7179:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7180: 	return 'error: no such course';
                   7181:     }
1.271     www      7182: # ----------------------------------------------------------------- Course made
1.516     raeburn  7183: # log existence
1.1029    raeburn  7184:     my $now = time;
1.918     raeburn  7185:     my $newcourse = {
                   7186:                     $udom.'_'.$uname => {
1.921     raeburn  7187:                                      description => $description,
                   7188:                                      inst_code   => $inst_code,
                   7189:                                      owner       => $course_owner,
                   7190:                                      type        => $crstype,
1.1029    raeburn  7191:                                      creator     => $env{'user.name'}.':'.
                   7192:                                                     $env{'user.domain'},
                   7193:                                      created     => $now,
                   7194:                                      context     => $context,
1.918     raeburn  7195:                                                 },
                   7196:                     };
1.921     raeburn  7197:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7198: # set toplevel url
1.271     www      7199:     my $topurl=$url;
                   7200:     unless ($nonstandard) {
                   7201: # ------------------------------------------ For standard courses, make top url
                   7202:         my $mapurl=&clutter($url);
1.278     www      7203:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7204:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7205: <map>
                   7206: <resource id="1" type="start"></resource>
                   7207: <resource id="2" src="$mapurl"></resource>
                   7208: <resource id="3" type="finish"></resource>
                   7209: <link index="1" from="1" to="2"></link>
                   7210: <link index="2" from="2" to="3"></link>
                   7211: </map>
                   7212: ENDINITMAP
                   7213:         $topurl=&declutter(
1.638     albertel 7214:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7215:                           );
                   7216:     }
                   7217: # ----------------------------------------------------------- Write preferences
1.84      www      7218:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7219:                      ('description'              => $description,
                   7220:                       'url'                      => $topurl,
                   7221:                       'internal.creator'         => $env{'user.name'}.':'.
                   7222:                                                     $env{'user.domain'},
                   7223:                       'internal.created'         => $now,
                   7224:                       'internal.creationcontext' => $context)
                   7225:                     );
1.84      www      7226:     return '/'.$udom.'/'.$uname;
                   7227: }
                   7228: 
1.1011    raeburn  7229: # ------------------------------------------------------------------- Create ID
                   7230: sub generate_coursenum {
1.1038    raeburn  7231:     my ($udom,$crstype) = @_;
1.1011    raeburn  7232:     my $domdesc = &domain($udom);
                   7233:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7234:     my $first;
                   7235:     if ($crstype eq 'Community') {
                   7236:         $first = '0';
                   7237:     } else {
                   7238:         $first = int(1+rand(9)); 
                   7239:     } 
                   7240:     my $uname=$first.
1.1011    raeburn  7241:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7242:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7243:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7244: # ----------------------------------------------- Make sure that does not exist
                   7245:     my $uhome=&homeserver($uname,$udom,'true');
                   7246:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7247:         if ($crstype eq 'Community') {
                   7248:             $first = '0';
                   7249:         } else {
                   7250:             $first = int(1+rand(9));
                   7251:         }
                   7252:         $uname=$first.
1.1011    raeburn  7253:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7254:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7255:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7256:         $uhome=&homeserver($uname,$udom,'true');
                   7257:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7258:             return 'error: unable to generate unique course-ID';
                   7259:         }
                   7260:     }
                   7261:     return $uname;
                   7262: }
                   7263: 
1.813     albertel 7264: sub is_course {
                   7265:     my ($cdom,$cnum) = @_;
                   7266:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7267: 				undef,'.');
1.813     albertel 7268:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7269:         return 1;
                   7270:     }
                   7271:     return 0;
                   7272: }
                   7273: 
1.1015    raeburn  7274: sub store_userdata {
                   7275:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7276:     my $result;
1.1016    raeburn  7277:     if ($datakey ne '') {
1.1013    raeburn  7278:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7279:             if ($udom eq '' || $uname eq '') {
                   7280:                 $udom = $env{'user.domain'};
                   7281:                 $uname = $env{'user.name'};
                   7282:             }
                   7283:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7284:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7285:                 $result = 'error: no_host';
                   7286:             } else {
                   7287:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7288:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7289: 
                   7290:                 my $namevalue='';
                   7291:                 foreach my $key (keys(%{$storehash})) {
                   7292:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7293:                 }
                   7294:                 $namevalue=~s/\&$//;
1.1105  ! raeburn  7295:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
        !          7296:                                   $namevalue,$uhome);
1.1013    raeburn  7297:             }
                   7298:         } else {
                   7299:             $result = 'error: data to store was not a hash reference'; 
                   7300:         }
                   7301:     } else {
                   7302:         $result= 'error: invalid requestkey'; 
                   7303:     }
                   7304:     return $result;
                   7305: }
                   7306: 
1.21      www      7307: # ---------------------------------------------------------- Assign Custom Role
                   7308: 
                   7309: sub assigncustomrole {
1.957     raeburn  7310:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7311:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7312:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7313: }
                   7314: 
                   7315: # ----------------------------------------------------------------- Revoke Role
                   7316: 
                   7317: sub revokerole {
1.957     raeburn  7318:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7319:     my $now=time;
1.965     raeburn  7320:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7321: }
                   7322: 
                   7323: # ---------------------------------------------------------- Revoke Custom Role
                   7324: 
                   7325: sub revokecustomrole {
1.957     raeburn  7326:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7327:     my $now=time;
1.357     www      7328:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7329:            $deleteflag,$selfenroll,$context);
1.17      www      7330: }
                   7331: 
1.533     banghart 7332: # ------------------------------------------------------------ Disk usage
1.535     albertel 7333: sub diskusage {
1.955     raeburn  7334:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7335:     $directorypath =~ s/\/$//;
                   7336:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7337:                        .&escape($getpropath).':'.&escape($uname).':'
                   7338:                        .&escape($udom),homeserver($uname,$udom));
                   7339:     if ($listing eq 'unknown_cmd') {
                   7340:         if ($getpropath) {
                   7341:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7342:         }
                   7343:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7344:     }
1.514     albertel 7345:     return $listing;
1.512     banghart 7346: }
                   7347: 
1.566     banghart 7348: sub is_locked {
1.1096    raeburn  7349:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7350:     my @check;
                   7351:     my $is_locked;
1.1093    raeburn  7352:     push (@check,$file_name);
1.613     albertel 7353:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7354: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7355:     my ($tmp)=keys(%locked);
                   7356:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7357:     
1.566     banghart 7358:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7359:         $is_locked = 'false';
                   7360:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7361:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7362:                $is_locked = 'true';
1.1096    raeburn  7363:                if (ref($which) eq 'ARRAY') {
                   7364:                    push(@{$which},$entry);
                   7365:                } else {
                   7366:                    last;
                   7367:                }
1.745     raeburn  7368:            }
                   7369:        }
1.566     banghart 7370:     } else {
                   7371:         $is_locked = 'false';
                   7372:     }
1.1093    raeburn  7373:     return $is_locked;
1.566     banghart 7374: }
                   7375: 
1.759     albertel 7376: sub declutter_portfile {
                   7377:     my ($file) = @_;
1.833     albertel 7378:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7379:     return $file;
                   7380: }
                   7381: 
1.559     banghart 7382: # ------------------------------------------------------------- Mark as Read Only
                   7383: 
                   7384: sub mark_as_readonly {
                   7385:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7386:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7387:     my ($tmp)=keys(%current_permissions);
                   7388:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7389:     foreach my $file (@{$files}) {
1.759     albertel 7390: 	$file = &declutter_portfile($file);
1.561     banghart 7391:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7392:     }
1.613     albertel 7393:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7394:     return;
                   7395: }
                   7396: 
1.572     banghart 7397: # ------------------------------------------------------------Save Selected Files
                   7398: 
                   7399: sub save_selected_files {
                   7400:     my ($user, $path, @files) = @_;
                   7401:     my $filename = $user."savedfiles";
1.573     banghart 7402:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7403:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7404:     foreach my $file (@files) {
1.620     albertel 7405:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7406:     }
                   7407:     foreach my $file (@other_files) {
1.574     banghart 7408:         print (OUT $file."\n");
1.572     banghart 7409:     }
1.574     banghart 7410:     close (OUT);
1.572     banghart 7411:     return 'ok';
                   7412: }
                   7413: 
1.574     banghart 7414: sub clear_selected_files {
                   7415:     my ($user) = @_;
                   7416:     my $filename = $user."savedfiles";
                   7417:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7418:     print (OUT undef);
                   7419:     close (OUT);
                   7420:     return ("ok");    
                   7421: }
                   7422: 
1.572     banghart 7423: sub files_in_path {
                   7424:     my ($user, $path) = @_;
                   7425:     my $filename = $user."savedfiles";
                   7426:     my %return_files;
1.574     banghart 7427:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7428:     while (my $line_in = <IN>) {
1.574     banghart 7429:         chomp ($line_in);
                   7430:         my @paths_and_file = split (m!/!, $line_in);
                   7431:         my $file_part = pop (@paths_and_file);
                   7432:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7433:         $path_part.='/';
                   7434:         my $path_and_file = $path_part.$file_part;
                   7435:         if ($path_part eq $path) {
                   7436:             $return_files{$file_part}= 'selected';
                   7437:         }
                   7438:     }
1.574     banghart 7439:     close (IN);
                   7440:     return (\%return_files);
1.572     banghart 7441: }
                   7442: 
                   7443: # called in portfolio select mode, to show files selected NOT in current directory
                   7444: sub files_not_in_path {
                   7445:     my ($user, $path) = @_;
                   7446:     my $filename = $user."savedfiles";
                   7447:     my @return_files;
                   7448:     my $path_part;
1.800     albertel 7449:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7450:     while (my $line = <IN>) {
1.572     banghart 7451:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7452:         my @paths_and_file = split(m|/|, $line);
                   7453:         my $file_part = pop(@paths_and_file);
                   7454:         chomp($file_part);
                   7455:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7456:         $path_part .= '/';
                   7457:         my $path_and_file = $path_part.$file_part;
                   7458:         if ($path_part ne $path) {
1.800     albertel 7459:             push(@return_files, ($path_and_file));
1.572     banghart 7460:         }
                   7461:     }
1.800     albertel 7462:     close(OUT);
1.574     banghart 7463:     return (@return_files);
1.572     banghart 7464: }
                   7465: 
1.745     raeburn  7466: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7467: 
1.745     raeburn  7468: sub get_portfile_permissions {
                   7469:     my ($domain,$user) = @_;
1.613     albertel 7470:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7471:     my ($tmp)=keys(%current_permissions);
                   7472:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7473:     return \%current_permissions;
                   7474: }
                   7475: 
                   7476: #---------------------------------------------Get portfolio file access controls
                   7477: 
1.749     raeburn  7478: sub get_access_controls {
1.745     raeburn  7479:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7480:     my %access;
                   7481:     my $real_file = $file;
                   7482:     $file =~ s/\.meta$//;
1.745     raeburn  7483:     if (defined($file)) {
1.749     raeburn  7484:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7485:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7486:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7487:             }
                   7488:         }
1.745     raeburn  7489:     } else {
1.749     raeburn  7490:         foreach my $key (keys(%{$current_permissions})) {
                   7491:             if ($key =~ /\0accesscontrol$/) {
                   7492:                 if (defined($group)) {
                   7493:                     if ($key !~ m-^\Q$group\E/-) {
                   7494:                         next;
                   7495:                     }
                   7496:                 }
                   7497:                 my ($fullpath) = split(/\0/,$key);
                   7498:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7499:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7500:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7501:                     }
                   7502:                 }
                   7503:             }
                   7504:         }
                   7505:     }
                   7506:     return %access;
                   7507: }
                   7508: 
                   7509: sub modify_access_controls {
                   7510:     my ($file_name,$changes,$domain,$user)=@_;
                   7511:     my ($outcome,$deloutcome);
                   7512:     my %store_permissions;
                   7513:     my %new_values;
                   7514:     my %new_control;
                   7515:     my %translation;
                   7516:     my @deletions = ();
                   7517:     my $now = time;
                   7518:     if (exists($$changes{'activate'})) {
                   7519:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7520:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7521:             my $numnew = scalar(@newitems);
                   7522:             for (my $i=0; $i<$numnew; $i++) {
                   7523:                 my $newkey = $newitems[$i];
                   7524:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7525:                 if ($newkey =~ /^\d+:/) { 
                   7526:                     $newkey =~ s/^(\d+)/$newid/;
                   7527:                     $translation{$1} = $newid;
                   7528:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7529:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7530:                     $translation{$1} = $newid;
                   7531:                 }
1.749     raeburn  7532:                 $new_values{$file_name."\0".$newkey} = 
                   7533:                                           $$changes{'activate'}{$newitems[$i]};
                   7534:                 $new_control{$newkey} = $now;
                   7535:             }
                   7536:         }
                   7537:     }
                   7538:     my %todelete;
                   7539:     my %changed_items;
                   7540:     foreach my $action ('delete','update') {
                   7541:         if (exists($$changes{$action})) {
                   7542:             if (ref($$changes{$action}) eq 'HASH') {
                   7543:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7544:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7545:                     if ($action eq 'delete') { 
                   7546:                         $todelete{$itemnum} = 1;
                   7547:                     } else {
                   7548:                         $changed_items{$itemnum} = $key;
                   7549:                     }
                   7550:                 }
1.745     raeburn  7551:             }
                   7552:         }
1.749     raeburn  7553:     }
                   7554:     # get lock on access controls for file.
                   7555:     my $lockhash = {
                   7556:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7557:                                                        ':'.$env{'user.domain'},
                   7558:                    }; 
                   7559:     my $tries = 0;
                   7560:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7561:    
                   7562:     while (($gotlock ne 'ok') && $tries <3) {
                   7563:         $tries ++;
                   7564:         sleep 1;
                   7565:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7566:     }
                   7567:     if ($gotlock eq 'ok') {
                   7568:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7569:         my ($tmp)=keys(%curr_permissions);
                   7570:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7571:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7572:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7573:             if (ref($curr_controls) eq 'HASH') {
                   7574:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7575:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7576:                     if (defined($todelete{$itemnum})) {
                   7577:                         push(@deletions,$file_name."\0".$control_item);
                   7578:                     } else {
                   7579:                         if (defined($changed_items{$itemnum})) {
                   7580:                             $new_control{$changed_items{$itemnum}} = $now;
                   7581:                             push(@deletions,$file_name."\0".$control_item);
                   7582:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7583:                         } else {
                   7584:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7585:                         }
                   7586:                     }
1.745     raeburn  7587:                 }
                   7588:             }
                   7589:         }
1.970     raeburn  7590:         my ($group);
                   7591:         if (&is_course($domain,$user)) {
                   7592:             ($group,my $file) = split(/\//,$file_name,2);
                   7593:         }
1.749     raeburn  7594:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7595:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7596:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7597:         #  remove lock
                   7598:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7599:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7600:         my $sqlresult =
1.970     raeburn  7601:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7602:                                     $group);
1.749     raeburn  7603:     } else {
                   7604:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7605:     }
1.749     raeburn  7606:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7607: }
                   7608: 
1.827     raeburn  7609: sub make_public_indefinitely {
                   7610:     my ($requrl) = @_;
                   7611:     my $now = time;
                   7612:     my $action = 'activate';
                   7613:     my $aclnum = 0;
                   7614:     if (&is_portfolio_url($requrl)) {
                   7615:         my (undef,$udom,$unum,$file_name,$group) =
                   7616:             &parse_portfolio_url($requrl);
                   7617:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7618:         my %access_controls = &get_access_controls($current_perms,
                   7619:                                                    $group,$file_name);
                   7620:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7621:             my ($num,$scope,$end,$start) = 
                   7622:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7623:             if ($scope eq 'public') {
                   7624:                 if ($start <= $now && $end == 0) {
                   7625:                     $action = 'none';
                   7626:                 } else {
                   7627:                     $action = 'update';
                   7628:                     $aclnum = $num;
                   7629:                 }
                   7630:                 last;
                   7631:             }
                   7632:         }
                   7633:         if ($action eq 'none') {
                   7634:              return 'ok';
                   7635:         } else {
                   7636:             my %changes;
                   7637:             my $newend = 0;
                   7638:             my $newstart = $now;
                   7639:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7640:             $changes{$action}{$newkey} = {
                   7641:                 type => 'public',
                   7642:                 time => {
                   7643:                     start => $newstart,
                   7644:                     end   => $newend,
                   7645:                 },
                   7646:             };
                   7647:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7648:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7649:             return $outcome;
                   7650:         }
                   7651:     } else {
                   7652:         return 'invalid';
                   7653:     }
                   7654: }
                   7655: 
1.745     raeburn  7656: #------------------------------------------------------Get Marked as Read Only
                   7657: 
                   7658: sub get_marked_as_readonly {
                   7659:     my ($domain,$user,$what,$group) = @_;
                   7660:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7661:     my @readonly_files;
1.629     banghart 7662:     my $cmp1=$what;
                   7663:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7664:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7665:         if (defined($group)) {
                   7666:             if ($file_name !~ m-^\Q$group\E/-) {
                   7667:                 next;
                   7668:             }
                   7669:         }
1.561     banghart 7670:         if (ref($value) eq "ARRAY"){
                   7671:             foreach my $stored_what (@{$value}) {
1.629     banghart 7672:                 my $cmp2=$stored_what;
1.759     albertel 7673:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7674:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7675:                 }
1.629     banghart 7676:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7677:                     push(@readonly_files, $file_name);
1.745     raeburn  7678:                     last;
1.563     banghart 7679:                 } elsif (!defined($what)) {
                   7680:                     push(@readonly_files, $file_name);
1.745     raeburn  7681:                     last;
1.561     banghart 7682:                 }
                   7683:             }
1.745     raeburn  7684:         }
1.561     banghart 7685:     }
                   7686:     return @readonly_files;
                   7687: }
1.577     banghart 7688: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7689: 
1.577     banghart 7690: sub get_marked_as_readonly_hash {
1.745     raeburn  7691:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7692:     my %readonly_files;
1.745     raeburn  7693:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7694:         if (defined($group)) {
                   7695:             if ($file_name !~ m-^\Q$group\E/-) {
                   7696:                 next;
                   7697:             }
                   7698:         }
1.577     banghart 7699:         if (ref($value) eq "ARRAY"){
                   7700:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7701:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7702:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7703:                         if ($lock_descriptor eq 'graded') {
                   7704:                             $readonly_files{$file_name} = 'graded';
                   7705:                         } elsif ($lock_descriptor eq 'handback') {
                   7706:                             $readonly_files{$file_name} = 'handback';
                   7707:                         } else {
                   7708:                             if (!exists($readonly_files{$file_name})) {
                   7709:                                 $readonly_files{$file_name} = 'locked';
                   7710:                             }
                   7711:                         }
1.745     raeburn  7712:                     }
1.750     banghart 7713:                 } 
1.577     banghart 7714:             }
                   7715:         } 
                   7716:     }
                   7717:     return %readonly_files;
                   7718: }
1.559     banghart 7719: # ------------------------------------------------------------ Unmark as Read Only
                   7720: 
                   7721: sub unmark_as_readonly {
1.629     banghart 7722:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7723:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7724:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7725:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7726:     my $symb_crs = $what;
                   7727:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7728:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7729:     my ($tmp)=keys(%current_permissions);
                   7730:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7731:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7732:     foreach my $file (@readonly_files) {
1.759     albertel 7733: 	my $clean_file = &declutter_portfile($file);
                   7734: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7735: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7736:         my @new_locks;
                   7737:         my @del_keys;
                   7738:         if (ref($current_locks) eq "ARRAY"){
                   7739:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7740:                 my $compare=$locker;
1.749     raeburn  7741:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7742:                     $compare=join('',@{$locker});
1.746     raeburn  7743:                     if ($compare ne $symb_crs) {
                   7744:                         push(@new_locks, $locker);
                   7745:                     }
1.563     banghart 7746:                 }
                   7747:             }
1.650     albertel 7748:             if (scalar(@new_locks) > 0) {
1.563     banghart 7749:                 $current_permissions{$file} = \@new_locks;
                   7750:             } else {
                   7751:                 push(@del_keys, $file);
1.613     albertel 7752:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7753:                 delete($current_permissions{$file});
1.563     banghart 7754:             }
                   7755:         }
1.561     banghart 7756:     }
1.613     albertel 7757:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7758:     return;
                   7759: }
1.512     banghart 7760: 
1.17      www      7761: # ------------------------------------------------------------ Directory lister
                   7762: 
                   7763: sub dirlist {
1.955     raeburn  7764:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7765:     $uri=~s/^\///;
                   7766:     $uri=~s/\/$//;
1.253     stredwic 7767:     my ($udom, $uname);
1.955     raeburn  7768:     if ($getuserdir) {
1.253     stredwic 7769:         $udom = $userdomain;
                   7770:         $uname = $username;
1.955     raeburn  7771:     } else {
                   7772:         (undef,$udom,$uname)=split(/\//,$uri);
                   7773:         if(defined($userdomain)) {
                   7774:             $udom = $userdomain;
                   7775:         }
                   7776:         if(defined($username)) {
                   7777:             $uname = $username;
                   7778:         }
1.253     stredwic 7779:     }
1.955     raeburn  7780:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7781: 
1.955     raeburn  7782:     $dirRoot = $perlvar{'lonDocRoot'};
                   7783:     if (defined($getpropath)) {
                   7784:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7785:         $dirRoot =~ s/\/$//;
1.955     raeburn  7786:     } elsif (defined($getuserdir)) {
                   7787:         my $subdir=$uname.'__';
                   7788:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7789:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7790:                    ."/$udom/$subdir/$uname";
                   7791:     } elsif (defined($alternateRoot)) {
                   7792:         $dirRoot = $alternateRoot;
1.751     banghart 7793:     }
1.253     stredwic 7794: 
                   7795:     if($udom) {
                   7796:         if($uname) {
1.955     raeburn  7797:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7798:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7799:                               .':'.&escape($uname).':'.&escape($udom),
                   7800:                               &homeserver($uname,$udom));
                   7801:             if ($listing eq 'unknown_cmd') {
                   7802:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7803:                                   &homeserver($uname,$udom));
                   7804:             } else {
                   7805:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7806:             }
1.605     matthew  7807:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7808:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7809: 				  &homeserver($uname,$udom));
1.605     matthew  7810:                 @listing_results = split(/:/,$listing);
                   7811:             } else {
                   7812:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7813:             }
                   7814:             return @listing_results;
1.955     raeburn  7815:         } elsif(!$alternateRoot) {
1.800     albertel 7816:             my %allusers;
1.841     albertel 7817: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7818:  	    foreach my $tryserver (keys(%servers)) {
                   7819:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7820:                                   &escape($udom),$tryserver);
                   7821:                 if ($listing eq 'unknown_cmd') {
                   7822: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7823: 				      $udom, $tryserver);
                   7824:                 } else {
                   7825:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7826:                 }
1.841     albertel 7827: 		if ($listing eq 'unknown_cmd') {
                   7828: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7829: 				      $udom, $tryserver);
                   7830: 		    @listing_results = split(/:/,$listing);
                   7831: 		} else {
                   7832: 		    @listing_results =
                   7833: 			map { &unescape($_); } split(/:/,$listing);
                   7834: 		}
                   7835: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7836: 		    $listing_results[0] ne 'empty'       &&
                   7837: 		    $listing_results[0] ne 'con_lost') {
                   7838: 		    foreach my $line (@listing_results) {
                   7839: 			my ($entry) = split(/&/,$line,2);
                   7840: 			$allusers{$entry} = 1;
                   7841: 		    }
                   7842: 		}
1.253     stredwic 7843:             }
                   7844:             my $alluserstr='';
1.800     albertel 7845:             foreach my $user (sort(keys(%allusers))) {
                   7846:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7847:             }
                   7848:             $alluserstr=~s/:$//;
                   7849:             return split(/:/,$alluserstr);
                   7850:         } else {
1.800     albertel 7851:             return ('missing user name');
1.253     stredwic 7852:         }
1.955     raeburn  7853:     } elsif(!defined($getpropath)) {
1.841     albertel 7854:         my @all_domains = sort(&all_domains());
1.955     raeburn  7855:         foreach my $domain (@all_domains) {
                   7856:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7857:         }
                   7858:         return @all_domains;
                   7859:     } else {
1.800     albertel 7860:         return ('missing domain');
1.275     stredwic 7861:     }
                   7862: }
                   7863: 
                   7864: # --------------------------------------------- GetFileTimestamp
                   7865: # This function utilizes dirlist and returns the date stamp for
                   7866: # when it was last modified.  It will also return an error of -1
                   7867: # if an error occurs
                   7868: 
                   7869: sub GetFileTimestamp {
1.955     raeburn  7870:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7871:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7872:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7873:     my ($fileStat) = 
                   7874:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7875:                                  undef,$getuserdir);
1.275     stredwic 7876:     my @stats = split('&', $fileStat);
                   7877:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7878:         # @stats contains first the filename, then the stat output
                   7879:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7880:     } else {
                   7881:         return -1;
1.253     stredwic 7882:     }
1.26      www      7883: }
                   7884: 
1.712     albertel 7885: sub stat_file {
                   7886:     my ($uri) = @_;
1.787     albertel 7887:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7888: 
1.955     raeburn  7889:     my ($udom,$uname,$file);
1.712     albertel 7890:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7891: 	($udom,$uname,$file) =
1.811     albertel 7892: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7893: 	$file = 'userfiles/'.$file;
                   7894:     }
                   7895:     if ($uri =~ m-^/res/-) {
                   7896: 	($udom,$uname) = 
1.807     albertel 7897: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7898: 	$file = $uri;
                   7899:     }
                   7900: 
                   7901:     if (!$udom || !$uname || !$file) {
                   7902: 	# unable to handle the uri
                   7903: 	return ();
                   7904:     }
1.956     raeburn  7905:     my $getpropath;
                   7906:     if ($file =~ /^userfiles\//) {
                   7907:         $getpropath = 1;
                   7908:     }
1.955     raeburn  7909:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7910:     my @stats = split('&', $result);
1.721     banghart 7911:     
1.712     albertel 7912:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7913: 	shift(@stats); #filename is first
                   7914: 	return @stats;
                   7915:     }
                   7916:     return ();
                   7917: }
                   7918: 
1.26      www      7919: # -------------------------------------------------------- Value of a Condition
                   7920: 
1.713     albertel 7921: # gets the value of a specific preevaluated condition
                   7922: #    stored in the string  $env{user.state.<cid>}
                   7923: # or looks up a condition reference in the bighash and if if hasn't
                   7924: # already been evaluated recurses into docondval to get the value of
                   7925: # the condition, then memoizing it to 
                   7926: #   $env{user.state.<cid>.<condition>}
1.40      www      7927: sub directcondval {
                   7928:     my $number=shift;
1.620     albertel 7929:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7930: 	&Apache::lonuserstate::evalstate();
                   7931:     }
1.713     albertel 7932:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7933: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7934:     } elsif ($number =~ /^_/) {
                   7935: 	my $sub_condition;
                   7936: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7937: 		&GDBM_READER(),0640)) {
                   7938: 	    $sub_condition=$bighash{'conditions'.$number};
                   7939: 	    untie(%bighash);
                   7940: 	}
                   7941: 	my $value = &docondval($sub_condition);
1.949     raeburn  7942: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7943: 	return $value;
                   7944:     }
1.620     albertel 7945:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7946:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7947:     } else {
                   7948:        return 2;
                   7949:     }
                   7950: }
                   7951: 
1.713     albertel 7952: # get the collection of conditions for this resource
1.26      www      7953: sub condval {
                   7954:     my $condidx=shift;
1.54      www      7955:     my $allpathcond='';
1.713     albertel 7956:     foreach my $cond (split(/\|/,$condidx)) {
                   7957: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7958: 	    $allpathcond.=
                   7959: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7960: 	}
1.191     harris41 7961:     }
1.54      www      7962:     $allpathcond=~s/\|$//;
1.713     albertel 7963:     return &docondval($allpathcond);
                   7964: }
                   7965: 
                   7966: #evaluates an expression of conditions
                   7967: sub docondval {
                   7968:     my ($allpathcond) = @_;
                   7969:     my $result=0;
                   7970:     if ($env{'request.course.id'}
                   7971: 	&& defined($allpathcond)) {
                   7972: 	my $operand='|';
                   7973: 	my @stack;
                   7974: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7975: 	    if ($chunk eq '(') {
                   7976: 		push @stack,($operand,$result);
                   7977: 	    } elsif ($chunk eq ')') {
                   7978: 		my $before=pop @stack;
                   7979: 		if (pop @stack eq '&') {
                   7980: 		    $result=$result>$before?$before:$result;
                   7981: 		} else {
                   7982: 		    $result=$result>$before?$result:$before;
                   7983: 		}
                   7984: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7985: 		$operand=$chunk;
                   7986: 	    } else {
                   7987: 		my $new=directcondval($chunk);
                   7988: 		if ($operand eq '&') {
                   7989: 		    $result=$result>$new?$new:$result;
                   7990: 		} else {
                   7991: 		    $result=$result>$new?$result:$new;
                   7992: 		}
                   7993: 	    }
                   7994: 	}
1.26      www      7995:     }
                   7996:     return $result;
1.421     albertel 7997: }
                   7998: 
                   7999: # ---------------------------------------------------- Devalidate courseresdata
                   8000: 
                   8001: sub devalidatecourseresdata {
                   8002:     my ($coursenum,$coursedomain)=@_;
                   8003:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8004:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8005: }
                   8006: 
1.763     www      8007: 
1.200     www      8008: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8009: #
                   8010: #  Parameters:
                   8011: #      $coursenum    - Number of the course.
                   8012: #      $coursedomain - Domain at which the course was created.
                   8013: #  Returns:
                   8014: #     A hash of the course parameters along (I think) with timestamps
                   8015: #     and version info.
1.877     foxr     8016: 
1.624     albertel 8017: sub get_courseresdata {
                   8018:     my ($coursenum,$coursedomain)=@_;
1.200     www      8019:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8020:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8021:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8022:     my %dumpreply;
1.417     albertel 8023:     unless (defined($cached)) {
1.624     albertel 8024: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8025: 	$result=\%dumpreply;
1.251     albertel 8026: 	my ($tmp) = keys(%dumpreply);
                   8027: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8028: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8029: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8030: 	    return $tmp;
1.416     albertel 8031: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8032: 	    $result=undef;
1.599     albertel 8033: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8034: 	}
                   8035:     }
1.624     albertel 8036:     return $result;
                   8037: }
                   8038: 
1.633     albertel 8039: sub devalidateuserresdata {
                   8040:     my ($uname,$udom)=@_;
                   8041:     my $hashid="$udom:$uname";
                   8042:     &devalidate_cache_new('userres',$hashid);
                   8043: }
                   8044: 
1.624     albertel 8045: sub get_userresdata {
                   8046:     my ($uname,$udom)=@_;
                   8047:     #most student don\'t have any data set, check if there is some data
                   8048:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8049: 
                   8050:     my $hashid="$udom:$uname";
                   8051:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8052:     if (!defined($cached)) {
                   8053: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8054: 	$result=\%resourcedata;
                   8055: 	&do_cache_new('userres',$hashid,$result,600);
                   8056:     }
                   8057:     my ($tmp)=keys(%$result);
                   8058:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8059: 	return $result;
                   8060:     }
                   8061:     #error 2 occurs when the .db doesn't exist
                   8062:     if ($tmp!~/error: 2 /) {
1.672     albertel 8063: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8064: 		 " Trying to get resource data for ".
                   8065: 		 $uname." at ".$udom.": ".
                   8066: 		 $tmp."</font>");
                   8067:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8068: 	#&EXT_cache_set($udom,$uname);
                   8069: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8070: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8071:     }
                   8072:     return $tmp;
                   8073: }
1.879     foxr     8074: #----------------------------------------------- resdata - return resource data
                   8075: #  Purpose:
                   8076: #    Return resource data for either users or for a course.
                   8077: #  Parameters:
                   8078: #     $name      - Course/user name.
                   8079: #     $domain    - Name of the domain the user/course is registered on.
                   8080: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8081: #     @which     - Array of names of resources desired.
                   8082: #  Returns:
                   8083: #     The value of the first reasource in @which that is found in the
                   8084: #     resource hash.
                   8085: #  Exceptional Conditions:
                   8086: #     If the $type passed in is not valid (not the string 'course' or 
                   8087: #     'user', an undefined  reference is returned.
                   8088: #     If none of the resources are found, an undef is returned
1.624     albertel 8089: sub resdata {
                   8090:     my ($name,$domain,$type,@which)=@_;
                   8091:     my $result;
                   8092:     if ($type eq 'course') {
                   8093: 	$result=&get_courseresdata($name,$domain);
                   8094:     } elsif ($type eq 'user') {
                   8095: 	$result=&get_userresdata($name,$domain);
                   8096:     }
                   8097:     if (!ref($result)) { return $result; }    
1.251     albertel 8098:     foreach my $item (@which) {
1.927     albertel 8099: 	if (defined($result->{$item->[0]})) {
                   8100: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8101: 	}
1.250     albertel 8102:     }
1.291     albertel 8103:     return undef;
1.200     www      8104: }
                   8105: 
1.379     matthew  8106: #
                   8107: # EXT resource caching routines
                   8108: #
                   8109: 
                   8110: sub clear_EXT_cache_status {
1.383     albertel 8111:     &delenv('cache.EXT.');
1.379     matthew  8112: }
                   8113: 
                   8114: sub EXT_cache_status {
                   8115:     my ($target_domain,$target_user) = @_;
1.383     albertel 8116:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8117:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8118:         # We know already the user has no data
                   8119:         return 1;
                   8120:     } else {
                   8121:         return 0;
                   8122:     }
                   8123: }
                   8124: 
                   8125: sub EXT_cache_set {
                   8126:     my ($target_domain,$target_user) = @_;
1.383     albertel 8127:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8128:     #&appenv({$cachename => time});
1.379     matthew  8129: }
                   8130: 
1.28      www      8131: # --------------------------------------------------------- Value of a Variable
1.58      www      8132: sub EXT {
1.715     albertel 8133: 
1.395     albertel 8134:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8135:     unless ($varname) { return ''; }
1.218     albertel 8136:     #get real user name/domain, courseid and symb
                   8137:     my $courseid;
1.359     albertel 8138:     my $publicuser;
1.427     www      8139:     if ($symbparm) {
                   8140: 	$symbparm=&get_symb_from_alias($symbparm);
                   8141:     }
1.218     albertel 8142:     if (!($uname && $udom)) {
1.790     albertel 8143:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8144:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8145:     } else {
1.620     albertel 8146: 	$courseid=$env{'request.course.id'};
1.218     albertel 8147:     }
1.48      www      8148:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8149:     my $rest;
1.320     albertel 8150:     if (defined($therest[0])) {
1.48      www      8151:        $rest=join('.',@therest);
                   8152:     } else {
                   8153:        $rest='';
                   8154:     }
1.320     albertel 8155: 
1.57      www      8156:     my $qualifierrest=$qualifier;
                   8157:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8158:     my $spacequalifierrest=$space;
                   8159:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8160:     if ($realm eq 'user') {
1.48      www      8161: # --------------------------------------------------------------- user.resource
                   8162: 	if ($space eq 'resource') {
1.651     albertel 8163: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8164: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8165: 		 &&
1.744     albertel 8166: 		 ($symbparm eq &symbread()) ) {	
                   8167: 		# if we are in the middle of processing the resource the
                   8168: 		# get the value we are planning on committing
                   8169:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8170:                     return $Apache::lonhomework::results{$qualifierrest};
                   8171:                 } else {
                   8172:                     return $Apache::lonhomework::history{$qualifierrest};
                   8173:                 }
1.335     albertel 8174: 	    } else {
1.359     albertel 8175: 		my %restored;
1.620     albertel 8176: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8177: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8178: 		} else {
                   8179: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8180: 		}
1.335     albertel 8181: 		return $restored{$qualifierrest};
                   8182: 	    }
1.48      www      8183: # ----------------------------------------------------------------- user.access
                   8184:         } elsif ($space eq 'access') {
1.218     albertel 8185: 	    # FIXME - not supporting calls for a specific user
1.48      www      8186:             return &allowed($qualifier,$rest);
                   8187: # ------------------------------------------ user.preferences, user.environment
                   8188:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8189: 	    if (($uname eq $env{'user.name'}) &&
                   8190: 		($udom eq $env{'user.domain'})) {
                   8191: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8192: 	    } else {
1.359     albertel 8193: 		my %returnhash;
                   8194: 		if (!$publicuser) {
                   8195: 		    %returnhash=&userenvironment($udom,$uname,
                   8196: 						 $qualifierrest);
                   8197: 		}
1.218     albertel 8198: 		return $returnhash{$qualifierrest};
                   8199: 	    }
1.48      www      8200: # ----------------------------------------------------------------- user.course
                   8201:         } elsif ($space eq 'course') {
1.218     albertel 8202: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8203:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8204: # ------------------------------------------------------------------- user.role
                   8205:         } elsif ($space eq 'role') {
1.218     albertel 8206: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8207:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8208:             if ($qualifier eq 'value') {
                   8209: 		return $role;
                   8210:             } elsif ($qualifier eq 'extent') {
                   8211:                 return $where;
                   8212:             }
                   8213: # ----------------------------------------------------------------- user.domain
                   8214:         } elsif ($space eq 'domain') {
1.218     albertel 8215:             return $udom;
1.48      www      8216: # ------------------------------------------------------------------- user.name
                   8217:         } elsif ($space eq 'name') {
1.218     albertel 8218:             return $uname;
1.48      www      8219: # ---------------------------------------------------- Any other user namespace
1.29      www      8220:         } else {
1.359     albertel 8221: 	    my %reply;
                   8222: 	    if (!$publicuser) {
                   8223: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8224: 	    }
                   8225: 	    return $reply{$qualifierrest};
1.48      www      8226:         }
1.236     www      8227:     } elsif ($realm eq 'query') {
                   8228: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8229:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8230: 						[$spacequalifierrest]);
1.620     albertel 8231: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8232:    } elsif ($realm eq 'request') {
1.48      www      8233: # ------------------------------------------------------------- request.browser
                   8234:         if ($space eq 'browser') {
1.430     www      8235: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8236: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8237: 		    return 1;
                   8238: 		} else {
                   8239: 		    return 0;
                   8240: 		}
                   8241: 	    } else {
1.620     albertel 8242: 		return $env{'browser.'.$qualifier};
1.430     www      8243: 	    }
1.57      www      8244: # ------------------------------------------------------------ request.filename
                   8245:         } else {
1.620     albertel 8246:             return $env{'request.'.$spacequalifierrest};
1.29      www      8247:         }
1.28      www      8248:     } elsif ($realm eq 'course') {
1.48      www      8249: # ---------------------------------------------------------- course.description
1.620     albertel 8250:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8251:     } elsif ($realm eq 'resource') {
1.165     www      8252: 
1.620     albertel 8253: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8254: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8255: 	}
1.693     albertel 8256: 
                   8257: 	if ($space eq 'title') {
                   8258: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8259: 	    return &gettitle($symbparm);
                   8260: 	}
                   8261: 	
                   8262: 	if ($space eq 'map') {
                   8263: 	    my ($map) = &decode_symb($symbparm);
                   8264: 	    return &symbread($map);
                   8265: 	}
1.905     albertel 8266: 	if ($space eq 'filename') {
                   8267: 	    if ($symbparm) {
                   8268: 		return &clutter((&decode_symb($symbparm))[2]);
                   8269: 	    }
                   8270: 	    return &hreflocation('',$env{'request.filename'});
                   8271: 	}
1.693     albertel 8272: 
                   8273: 	my ($section, $group, @groups);
1.593     albertel 8274: 	my ($courselevelm,$courselevel);
1.539     albertel 8275: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8276: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8277: 
1.218     albertel 8278: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8279: 
1.60      www      8280: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8281: 	    my $symbp=$symbparm;
1.735     albertel 8282: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8283: 
                   8284: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8285: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8286: 
1.620     albertel 8287: 	    if (($env{'user.name'} eq $uname) &&
                   8288: 		($env{'user.domain'} eq $udom)) {
                   8289: 		$section=$env{'request.course.sec'};
1.733     raeburn  8290:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8291:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8292: 	    } else {
1.539     albertel 8293: 		if (! defined($usection)) {
1.551     albertel 8294: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8295: 		} else {
                   8296: 		    $section = $usection;
                   8297: 		}
1.733     raeburn  8298:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8299: 	    }
                   8300: 
                   8301: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8302: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8303: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8304: 
1.593     albertel 8305: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8306: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8307: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8308: 
1.60      www      8309: # ----------------------------------------------------------- first, check user
1.624     albertel 8310: 
                   8311: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8312: 				       ([$courselevelr,'resource'],
                   8313: 					[$courselevelm,'map'     ],
                   8314: 					[$courselevel, 'course'  ]));
1.931     albertel 8315: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8316: 
1.594     albertel 8317: # ------------------------------------------------ second, check some of course
1.684     raeburn  8318:             my $coursereply;
1.691     raeburn  8319:             if (@groups > 0) {
                   8320:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8321:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8322:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8323:             }
1.96      www      8324: 
1.684     raeburn  8325: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8326: 				  $env{'course.'.$courseid.'.domain'},
                   8327: 				  'course',
                   8328: 				  ([$seclevelr,   'resource'],
                   8329: 				   [$seclevelm,   'map'     ],
                   8330: 				   [$seclevel,    'course'  ],
                   8331: 				   [$courselevelr,'resource']));
                   8332: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8333: 
1.60      www      8334: # ------------------------------------------------------ third, check map parms
1.218     albertel 8335: 	    my %parmhash=();
                   8336: 	    my $thisparm='';
                   8337: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8338: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8339: 		    &GDBM_READER(),0640)) {
1.218     albertel 8340: 		$thisparm=$parmhash{$symbparm};
                   8341: 		untie(%parmhash);
                   8342: 	    }
1.927     albertel 8343: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8344: 	}
1.594     albertel 8345: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8346: 
1.218     albertel 8347: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8348: 	my $filename;
                   8349: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8350: 	if ($symbparm) {
1.409     www      8351: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8352: 	} else {
1.620     albertel 8353: 	    $filename=$env{'request.filename'};
1.282     albertel 8354: 	}
                   8355: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8356: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8357: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8358: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8359: 
1.927     albertel 8360: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8361: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8362: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8363: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8364: 				     $env{'course.'.$courseid.'.domain'},
                   8365: 				     'course',
1.927     albertel 8366: 				     ([$courselevelm,'map'   ],
                   8367: 				      [$courselevel, 'course']));
                   8368: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8369: 	}
1.145     www      8370: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8371: 	unless ($space eq '0') {
1.336     albertel 8372: 	    my @parts=split(/_/,$space);
                   8373: 	    my $id=pop(@parts);
                   8374: 	    my $part=join('_',@parts);
                   8375: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8376: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8377: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8378: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8379: 	}
1.395     albertel 8380: 	if ($recurse) { return undef; }
                   8381: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8382: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8383: # ---------------------------------------------------- Any other user namespace
                   8384:     } elsif ($realm eq 'environment') {
                   8385: # ----------------------------------------------------------------- environment
1.620     albertel 8386: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8387: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8388: 	} else {
1.770     albertel 8389: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8390: 		return '';
                   8391: 	    }
1.219     albertel 8392: 	    my %returnhash=&userenvironment($udom,$uname,
                   8393: 					    $spacequalifierrest);
                   8394: 	    return $returnhash{$spacequalifierrest};
                   8395: 	}
1.28      www      8396:     } elsif ($realm eq 'system') {
1.48      www      8397: # ----------------------------------------------------------------- system.time
                   8398: 	if ($space eq 'time') {
                   8399: 	    return time;
                   8400:         }
1.696     albertel 8401:     } elsif ($realm eq 'server') {
                   8402: # ----------------------------------------------------------------- system.time
                   8403: 	if ($space eq 'name') {
                   8404: 	    return $ENV{'SERVER_NAME'};
                   8405:         }
1.28      www      8406:     }
1.48      www      8407:     return '';
1.61      www      8408: }
                   8409: 
1.927     albertel 8410: sub get_reply {
                   8411:     my ($reply_value) = @_;
1.940     raeburn  8412:     if (ref($reply_value) eq 'ARRAY') {
                   8413:         if (wantarray) {
                   8414: 	    return @$reply_value;
                   8415:         }
                   8416:         return $reply_value->[0];
                   8417:     } else {
                   8418:         return $reply_value;
1.927     albertel 8419:     }
                   8420: }
                   8421: 
1.691     raeburn  8422: sub check_group_parms {
                   8423:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8424:     my @groupitems = ();
                   8425:     my $resultitem;
1.927     albertel 8426:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8427:     foreach my $group (@{$groups}) {
                   8428:         foreach my $level (@levels) {
1.927     albertel 8429:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8430:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8431:         }
                   8432:     }
                   8433:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8434:                             $env{'course.'.$courseid.'.domain'},
                   8435:                                      'course',@groupitems);
                   8436:     return $coursereply;
                   8437: }
                   8438: 
                   8439: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8440:     my ($courseid,@groups) = @_;
                   8441:     @groups = sort(@groups);
1.691     raeburn  8442:     return @groups;
                   8443: }
                   8444: 
1.395     albertel 8445: sub packages_tab_default {
                   8446:     my ($uri,$varname)=@_;
                   8447:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8448: 
                   8449:     my (@extension,@specifics,$do_default);
                   8450:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8451: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8452: 	if ($pack_type eq 'default') {
                   8453: 	    $do_default=1;
                   8454: 	} elsif ($pack_type eq 'extension') {
                   8455: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8456: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8457: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8458: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8459: 	}
                   8460:     }
                   8461:     # first look for a package that matches the requested part id
                   8462:     foreach my $package (@specifics) {
                   8463: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8464: 	next if ($pack_part ne $part);
                   8465: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8466: 	    return $packagetab{"$pack_type&$name&default"};
                   8467: 	}
                   8468:     }
                   8469:     # look for any possible matching non extension_ package
                   8470:     foreach my $package (@specifics) {
                   8471: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8472: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8473: 	    return $packagetab{"$pack_type&$name&default"};
                   8474: 	}
1.585     albertel 8475: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8476: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8477: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8478: 	}
                   8479:     }
1.738     albertel 8480:     # look for any posible extension_ match
                   8481:     foreach my $package (@extension) {
                   8482: 	my ($package,$pack_type)=@{$package};
                   8483: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8484: 	    return $packagetab{"$pack_type&$name&default"};
                   8485: 	}
                   8486: 	if (defined($packagetab{$package."&$name&default"})) {
                   8487: 	    return $packagetab{$package."&$name&default"};
                   8488: 	}
                   8489:     }
                   8490:     # look for a global default setting
                   8491:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8492: 	return $packagetab{"default&$name&default"};
                   8493:     }
1.395     albertel 8494:     return undef;
                   8495: }
                   8496: 
1.334     albertel 8497: sub add_prefix_and_part {
                   8498:     my ($prefix,$part)=@_;
                   8499:     my $keyroot;
                   8500:     if (defined($prefix) && $prefix !~ /^__/) {
                   8501: 	# prefix that has a part already
                   8502: 	$keyroot=$prefix;
                   8503:     } elsif (defined($prefix)) {
                   8504: 	# prefix that is missing a part
                   8505: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8506:     } else {
                   8507: 	# no prefix at all
                   8508: 	if (defined($part)) { $keyroot='_'.$part; }
                   8509:     }
                   8510:     return $keyroot;
                   8511: }
                   8512: 
1.71      www      8513: # ---------------------------------------------------------------- Get metadata
                   8514: 
1.599     albertel 8515: my %metaentry;
1.1070    www      8516: my %importedpartids;
1.71      www      8517: sub metadata {
1.176     www      8518:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8519:     $uri=&declutter($uri);
1.288     albertel 8520:     # if it is a non metadata possible uri return quickly
1.529     albertel 8521:     if (($uri eq '') || 
                   8522: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8523: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1100    raeburn  8524:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$}) || ($uri =~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.924     albertel 8525: 	return undef;
                   8526:     }
                   8527:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8528: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8529: 	return undef;
1.288     albertel 8530:     }
1.73      www      8531:     my $filename=$uri;
                   8532:     $uri=~s/\.meta$//;
1.172     www      8533: #
                   8534: # Is the metadata already cached?
1.177     www      8535: # Look at timestamp of caching
1.172     www      8536: # Everything is cached by the main uri, libraries are never directly cached
                   8537: #
1.428     albertel 8538:     if (!defined($liburi)) {
1.599     albertel 8539: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8540: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8541:     }
                   8542:     {
1.1069    www      8543: # Imported parts would go here
1.1070    www      8544:         my %importedids=();
                   8545:         my @origfileimportpartids=();
1.1069    www      8546:         my $importedparts=0;
1.172     www      8547: #
                   8548: # Is this a recursive call for a library?
                   8549: #
1.599     albertel 8550: #	if (! exists($metacache{$uri})) {
                   8551: #	    $metacache{$uri}={};
                   8552: #	}
1.924     albertel 8553: 	my $cachetime = 60*60;
1.171     www      8554:         if ($liburi) {
                   8555: 	    $liburi=&declutter($liburi);
                   8556:             $filename=$liburi;
1.401     bowersj2 8557:         } else {
1.599     albertel 8558: 	    &devalidate_cache_new('meta',$uri);
                   8559: 	    undef(%metaentry);
1.401     bowersj2 8560: 	}
1.140     www      8561:         my %metathesekeys=();
1.73      www      8562:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8563: 	my $metastring;
1.924     albertel 8564: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8565: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8566: 	    $metastring = 
1.929     albertel 8567: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8568: 					  ('grade_target' => 'meta'));
                   8569: 	    $cachetime = 1; # only want this cached in the child not long term
                   8570: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8571: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8572: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8573: 	    $metastring=&getfile($file);
1.489     albertel 8574: 	}
1.208     albertel 8575:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8576:         my $token;
1.140     www      8577:         undef %metathesekeys;
1.71      www      8578:         while ($token=$parser->get_token) {
1.339     albertel 8579: 	    if ($token->[0] eq 'S') {
                   8580: 		if (defined($token->[2]->{'package'})) {
1.172     www      8581: #
                   8582: # This is a package - get package info
                   8583: #
1.339     albertel 8584: 		    my $package=$token->[2]->{'package'};
                   8585: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8586: 		    if (defined($token->[2]->{'id'})) { 
                   8587: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8588: 		    }
1.599     albertel 8589: 		    if ($metaentry{':packages'}) {
                   8590: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8591: 		    } else {
1.599     albertel 8592: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8593: 		    }
1.736     albertel 8594: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8595: 			my $part=$keyroot;
                   8596: 			$part=~s/^\_//;
1.736     albertel 8597: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8598: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8599: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8600: 			    # ignore package.tab specified default values
                   8601:                             # here &package_tab_default() will fetch those
                   8602: 			    if ($subp eq 'default') { next; }
1.736     albertel 8603: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8604: 			    my $unikey;
                   8605: 			    if ($pack =~ /_0$/) {
                   8606: 				$unikey='parameter_0_'.$name;
                   8607: 				$part=0;
                   8608: 			    } else {
                   8609: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8610: 			    }
1.339     albertel 8611: 			    if ($subp eq 'display') {
                   8612: 				$value.=' [Part: '.$part.']';
                   8613: 			    }
1.599     albertel 8614: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8615: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8616: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8617: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8618: 			    }
1.599     albertel 8619: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8620: 				$metaentry{':'.$unikey}=
                   8621: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8622: 			    }
1.339     albertel 8623: 			}
                   8624: 		    }
                   8625: 		} else {
1.172     www      8626: #
                   8627: # This is not a package - some other kind of start tag
1.339     albertel 8628: #
                   8629: 		    my $entry=$token->[1];
1.1068    www      8630: 		    my $unikey='';
1.175     www      8631: 
1.339     albertel 8632: 		    if ($entry eq 'import') {
1.175     www      8633: #
                   8634: # Importing a library here
1.339     albertel 8635: #
1.1067    www      8636:                         my $location=$parser->get_text('/import');
                   8637:                         my $dir=$filename;
                   8638:                         $dir=~s|[^/]*$||;
                   8639:                         $location=&filelocation($dir,$location);
1.1069    www      8640:                        
1.1068    www      8641:                         my $importmode=$token->[2]->{'importmode'};
                   8642:                         if ($importmode eq 'problem') {
1.1069    www      8643: # Import as problem/response
1.1068    www      8644:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8645:                         } elsif ($importmode eq 'part') {
                   8646: # Import as part(s)
1.1069    www      8647:                            $importedparts=1;
                   8648: # We need to get the original file and the imported file to get the part order correct
                   8649: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8650: # Load and inspect original file
1.1070    www      8651:                            if ($#origfileimportpartids<0) {
                   8652:                               undef(%importedpartids);
                   8653:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8654:                               my $origfile=&getfile($origfilelocation);
                   8655:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8656:                            }
                   8657: 
1.1069    www      8658: # Load and inspect imported file
                   8659:                            my $impfile=&getfile($location);
                   8660:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8661:                            if ($#impfilepartids>=0) {
                   8662: # This problem had parts
1.1070    www      8663:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8664:                            } else {
                   8665: # Importing by turning a single problem into a problem part
                   8666: # It gets the import-tags ID as part-ID
                   8667:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8668:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8669:                            }
1.1068    www      8670:                         } else {
                   8671: # Normal import
                   8672:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8673:                            if (defined($token->[2]->{'id'})) {
                   8674:                               $unikey.='_'.$token->[2]->{'id'};
                   8675:                            }
1.1067    www      8676:                         }
                   8677: 
1.339     albertel 8678: 			if ($depthcount<20) {
1.736     albertel 8679: 			    my $metadata = 
                   8680: 				&metadata($uri,'keys', $location,$unikey,
                   8681: 					  $depthcount+1);
                   8682: 			    foreach my $meta (split(',',$metadata)) {
                   8683: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8684: 				$metathesekeys{$meta}=1;
1.339     albertel 8685: 			    }
1.1068    www      8686: 			
                   8687:                         }
1.1067    www      8688: 		    } else {
                   8689: #
                   8690: # Not importing, some other kind of non-package, non-library start tag
                   8691: # 
                   8692:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8693:                         if (defined($token->[2]->{'id'})) {
                   8694:                             $unikey.='_'.$token->[2]->{'id'};
                   8695:                         }
1.339     albertel 8696: 			if (defined($token->[2]->{'name'})) { 
                   8697: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8698: 			}
                   8699: 			$metathesekeys{$unikey}=1;
1.736     albertel 8700: 			foreach my $param (@{$token->[3]}) {
                   8701: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8702: 				$token->[2]->{$param};
1.339     albertel 8703: 			}
                   8704: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8705: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8706: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8707: 		 # only ws inside the tag, and not in default, so use default
                   8708: 		 # as value
1.599     albertel 8709: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8710: 			} elsif ( $internaltext =~ /\S/ ) {
                   8711: 		  # something interesting inside the tag
                   8712: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8713: 			} else {
1.908     albertel 8714: 		  # no interesting values, don't set a default
1.339     albertel 8715: 			}
1.172     www      8716: # end of not-a-package not-a-library import
1.339     albertel 8717: 		    }
1.172     www      8718: # end of not-a-package start tag
1.339     albertel 8719: 		}
1.172     www      8720: # the next is the end of "start tag"
1.339     albertel 8721: 	    }
                   8722: 	}
1.483     albertel 8723: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8724: 	$extension = lc($extension);
                   8725: 	if ($extension eq 'htm') { $extension='html'; }
                   8726: 
1.737     albertel 8727: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8728: 	    #no specific packages #how's our extension
                   8729: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8730: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8731: 					 \%metathesekeys);
                   8732: 	}
1.883     albertel 8733: 
                   8734: 	if (!exists($metaentry{':packages'})
                   8735: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8736: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8737: 		#no specific packages well let's get default then
                   8738: 		if ($key!~/^default&/) { next; }
1.488     albertel 8739: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8740: 					     \%metathesekeys);
                   8741: 	    }
                   8742: 	}
1.338     www      8743: # are there custom rights to evaluate
1.599     albertel 8744: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8745: 
1.338     www      8746:     #
                   8747:     # Importing a rights file here
1.339     albertel 8748:     #
                   8749: 	    unless ($depthcount) {
1.599     albertel 8750: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8751: 		my $dir=$filename;
                   8752: 		$dir=~s|[^/]*$||;
                   8753: 		$location=&filelocation($dir,$location);
1.736     albertel 8754: 		my $rights_metadata =
                   8755: 		    &metadata($uri,'keys',$location,'_rights',
                   8756: 			      $depthcount+1);
                   8757: 		foreach my $rights (split(',',$rights_metadata)) {
                   8758: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8759: 		    $metathesekeys{$rights}=1;
1.339     albertel 8760: 		}
                   8761: 	    }
                   8762: 	}
1.737     albertel 8763: 	# uniqifiy package listing
                   8764: 	my %seen;
                   8765: 	my @uniq_packages =
                   8766: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8767: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8768: 
1.1070    www      8769:         if ($importedparts) {
                   8770: # We had imported parts and need to rebuild partorder
                   8771:            $metaentry{':partorder'}='';
                   8772:            $metathesekeys{'partorder'}=1;
                   8773:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8774:                if ($origfileimportpartids[$index] eq 'part') {
                   8775: # original part, part of the problem
                   8776:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8777:                } else {
                   8778: # we have imported parts at this position
                   8779:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8780:                }
                   8781:            }
                   8782:            $metaentry{':partorder'}=~s/^\,//;
                   8783:         }
                   8784: 
1.737     albertel 8785: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8786: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8787: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8788: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8789: # this is the end of "was not already recently cached
1.71      www      8790:     }
1.599     albertel 8791:     return $metaentry{':'.$what};
1.261     albertel 8792: }
                   8793: 
1.488     albertel 8794: sub metadata_create_package_def {
1.483     albertel 8795:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8796:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8797:     if ($subp eq 'default') { next; }
                   8798:     
1.599     albertel 8799:     if (defined($metaentry{':packages'})) {
                   8800: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8801:     } else {
1.599     albertel 8802: 	$metaentry{':packages'}=$package;
1.483     albertel 8803:     }
                   8804:     my $value=$packagetab{$key};
                   8805:     my $unikey;
                   8806:     $unikey='parameter_0_'.$name;
1.599     albertel 8807:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8808:     $$metathesekeys{$unikey}=1;
1.599     albertel 8809:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8810: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8811:     }
1.599     albertel 8812:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8813: 	$metaentry{':'.$unikey}=
                   8814: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8815:     }
                   8816: }
                   8817: 
1.261     albertel 8818: sub metadata_generate_part0 {
                   8819:     my ($metadata,$metacache,$uri) = @_;
                   8820:     my %allnames;
1.737     albertel 8821:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8822: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8823: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8824: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8825: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8826: 	    $allnames{$name}=$part;
                   8827: 	  }
                   8828: 	}
                   8829:     }
                   8830:     foreach my $name (keys(%allnames)) {
                   8831:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8832:       my $key=":parameter_0_$name";
1.261     albertel 8833:       $$metacache{"$key.part"}='0';
                   8834:       $$metacache{"$key.name"}=$name;
1.428     albertel 8835:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8836: 					   $allnames{$name}.'_'.$name.
                   8837: 					   '.type'};
1.428     albertel 8838:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8839: 			     '.display'};
1.644     www      8840:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8841:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8842:       $$metacache{"$key.display"}=$olddis;
                   8843:     }
1.71      www      8844: }
                   8845: 
1.764     albertel 8846: # ------------------------------------------------------ Devalidate title cache
                   8847: 
                   8848: sub devalidate_title_cache {
                   8849:     my ($url)=@_;
                   8850:     if (!$env{'request.course.id'}) { return; }
                   8851:     my $symb=&symbread($url);
                   8852:     if (!$symb) { return; }
                   8853:     my $key=$env{'request.course.id'}."\0".$symb;
                   8854:     &devalidate_cache_new('title',$key);
                   8855: }
                   8856: 
1.1014    droeschl 8857: # ------------------------------------------------- Get the title of a course
                   8858: 
                   8859: sub current_course_title {
                   8860:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8861: }
1.301     www      8862: # ------------------------------------------------- Get the title of a resource
                   8863: 
                   8864: sub gettitle {
                   8865:     my $urlsymb=shift;
                   8866:     my $symb=&symbread($urlsymb);
1.534     albertel 8867:     if ($symb) {
1.620     albertel 8868: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8869: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8870: 	if (defined($cached)) { 
                   8871: 	    return $result;
                   8872: 	}
1.534     albertel 8873: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8874: 	my $title='';
1.907     albertel 8875: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8876: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8877: 	} else {
                   8878: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8879: 		    &GDBM_READER(),0640)) {
                   8880: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8881: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8882: 		untie(%bighash);
                   8883: 	    }
1.534     albertel 8884: 	}
                   8885: 	$title=~s/\&colon\;/\:/gs;
                   8886: 	if ($title) {
1.599     albertel 8887: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8888: 	}
                   8889: 	$urlsymb=$url;
                   8890:     }
                   8891:     my $title=&metadata($urlsymb,'title');
                   8892:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8893:     return $title;
1.301     www      8894: }
1.613     albertel 8895: 
1.614     albertel 8896: sub get_slot {
                   8897:     my ($which,$cnum,$cdom)=@_;
                   8898:     if (!$cnum || !$cdom) {
1.790     albertel 8899: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8900: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8901: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8902:     }
1.703     albertel 8903:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8904:     my %slotinfo;
                   8905:     if (exists($remembered{$key})) {
                   8906: 	$slotinfo{$which} = $remembered{$key};
                   8907:     } else {
                   8908: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8909: 	&Apache::lonhomework::showhash(%slotinfo);
                   8910: 	my ($tmp)=keys(%slotinfo);
                   8911: 	if ($tmp=~/^error:/) { return (); }
                   8912: 	$remembered{$key} = $slotinfo{$which};
                   8913:     }
1.616     albertel 8914:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8915: 	return %{$slotinfo{$which}};
                   8916:     }
                   8917:     return $slotinfo{$which};
1.614     albertel 8918: }
1.31      www      8919: # ------------------------------------------------- Update symbolic store links
                   8920: 
                   8921: sub symblist {
                   8922:     my ($mapname,%newhash)=@_;
1.438     www      8923:     $mapname=&deversion(&declutter($mapname));
1.31      www      8924:     my %hash;
1.620     albertel 8925:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8926:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8927:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8928: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8929: 		next if ($url eq 'last_known'
                   8930: 			 && $env{'form.no_update_last_known'});
                   8931: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8932: 						    $newhash{$url}->[1],
                   8933: 						    $newhash{$url}->[0]);
1.191     harris41 8934:             }
1.31      www      8935:             if (untie(%hash)) {
                   8936: 		return 'ok';
                   8937:             }
                   8938:         }
                   8939:     }
                   8940:     return 'error';
1.212     www      8941: }
                   8942: 
                   8943: # --------------------------------------------------------------- Verify a symb
                   8944: 
                   8945: sub symbverify {
1.510     www      8946:     my ($symb,$thisurl)=@_;
                   8947:     my $thisfn=$thisurl;
1.439     www      8948:     $thisfn=&declutter($thisfn);
1.215     www      8949: # direct jump to resource in page or to a sequence - will construct own symbs
                   8950:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8951: # check URL part
1.409     www      8952:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8953: 
1.431     www      8954:     unless ($url eq $thisfn) { return 0; }
1.213     www      8955: 
1.216     www      8956:     $symb=&symbclean($symb);
1.510     www      8957:     $thisurl=&deversion($thisurl);
1.439     www      8958:     $thisfn=&deversion($thisfn);
1.213     www      8959: 
                   8960:     my %bighash;
                   8961:     my $okay=0;
1.431     www      8962: 
1.620     albertel 8963:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8964:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8965:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8966:             $thisurl =~ s/\?.+$//;
                   8967:         }
1.510     www      8968:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  8969:         unless ($ids) {
                   8970:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   8971:             $ids=$bighash{$idkey};
1.216     www      8972:         }
                   8973:         if ($ids) {
                   8974: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8975: 	    foreach my $id (split(/\,/,$ids)) {
                   8976: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8977:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8978:                    $symb =~ s/\?.+$//;
                   8979:                }
1.216     www      8980:                if (
                   8981:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8982:    eq $symb) { 
1.620     albertel 8983: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  8984: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   8985:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 8986: 		       $okay=1; 
                   8987: 		   }
                   8988: 	       }
1.216     www      8989: 	   }
                   8990:         }
1.213     www      8991: 	untie(%bighash);
                   8992:     }
                   8993:     return $okay;
1.31      www      8994: }
                   8995: 
1.210     www      8996: # --------------------------------------------------------------- Clean-up symb
                   8997: 
                   8998: sub symbclean {
                   8999:     my $symb=shift;
1.568     albertel 9000:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9001: # remove version from map
                   9002:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9003: 
1.210     www      9004: # remove version from URL
                   9005:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9006: 
1.507     www      9007: # remove wrapper
                   9008: 
1.510     www      9009:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9010:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9011:     return $symb;
1.409     www      9012: }
                   9013: 
                   9014: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9015: 
                   9016: sub encode_symb {
                   9017:     my ($map,$resid,$url)=@_;
                   9018:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9019: }
1.409     www      9020: 
                   9021: sub decode_symb {
1.568     albertel 9022:     my $symb=shift;
                   9023:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9024:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9025:     return (&fixversion($map),$resid,&fixversion($url));
                   9026: }
                   9027: 
                   9028: sub fixversion {
                   9029:     my $fn=shift;
1.609     banghart 9030:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9031:     my %bighash;
                   9032:     my $uri=&clutter($fn);
1.620     albertel 9033:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9034: # is this cached?
1.599     albertel 9035:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9036:     if (defined($cached)) { return $result; }
                   9037: # unfortunately not cached, or expired
1.620     albertel 9038:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9039: 	    &GDBM_READER(),0640)) {
                   9040:  	if ($bighash{'version_'.$uri}) {
                   9041:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9042:  	    unless (($version eq 'mostrecent') || 
                   9043: 		    ($version==&getversion($uri))) {
1.440     www      9044:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9045:  	    }
                   9046:  	}
                   9047:  	untie %bighash;
1.413     www      9048:     }
1.599     albertel 9049:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9050: }
                   9051: 
                   9052: sub deversion {
                   9053:     my $url=shift;
                   9054:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9055:     return $url;
1.210     www      9056: }
                   9057: 
1.31      www      9058: # ------------------------------------------------------ Return symb list entry
                   9059: 
                   9060: sub symbread {
1.249     www      9061:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9062:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9063:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9064: # no filename provided? try from environment
1.44      www      9065:     unless ($thisfn) {
1.620     albertel 9066:         if ($env{'request.symb'}) {
                   9067: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9068: 	}
1.620     albertel 9069: 	$thisfn=$env{'request.filename'};
1.44      www      9070:     }
1.569     albertel 9071:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9072: # is that filename actually a symb? Verify, clean, and return
                   9073:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9074: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9075: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9076: 	}
1.242     www      9077:     }
1.44      www      9078:     $thisfn=declutter($thisfn);
1.31      www      9079:     my %hash;
1.37      www      9080:     my %bighash;
                   9081:     my $syval='';
1.620     albertel 9082:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9083:         my $targetfn = $thisfn;
1.609     banghart 9084:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9085:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9086:         }
1.687     albertel 9087: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9088: 	    $targetfn=$1;
                   9089: 	}
1.620     albertel 9090:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9091:                       &GDBM_READER(),0640)) {
1.481     raeburn  9092: 	    $syval=$hash{$targetfn};
1.37      www      9093:             untie(%hash);
                   9094:         }
                   9095: # ---------------------------------------------------------- There was an entry
                   9096:         if ($syval) {
1.601     albertel 9097: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9098: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9099: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9100: 		    #return $env{$cache_str}='';
1.601     albertel 9101: 		#}    
                   9102: 		#$syval.=$1;
                   9103: 	    #}
1.37      www      9104:         } else {
                   9105: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9106:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9107:                             &GDBM_READER(),0640)) {
1.37      www      9108: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9109:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9110:               unless ($ids) { 
                   9111:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9112:               }
                   9113:               unless ($ids) {
                   9114: # alias?
                   9115: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9116:               }
1.37      www      9117:               if ($ids) {
                   9118: # ------------------------------------------------------------------- Has ID(s)
                   9119:                  my @possibilities=split(/\,/,$ids);
1.39      www      9120:                  if ($#possibilities==0) {
                   9121: # ----------------------------------------------- There is only one possibility
1.37      www      9122: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9123: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9124: 						    $resid,$thisfn);
1.249     www      9125:                  } elsif (!$donotrecurse) {
1.39      www      9126: # ------------------------------------------ There is more than one possibility
                   9127:                      my $realpossible=0;
1.800     albertel 9128:                      foreach my $id (@possibilities) {
                   9129: 			 my $file=$bighash{'src_'.$id};
1.39      www      9130:                          if (&allowed('bre',$file)) {
1.800     albertel 9131:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9132:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9133: 				$realpossible++;
1.626     albertel 9134:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9135: 						    $resid,$thisfn);
1.39      www      9136:                             }
                   9137: 			 }
1.191     harris41 9138:                      }
1.39      www      9139: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9140:                  } else {
                   9141:                      $syval='';
1.37      www      9142:                  }
                   9143: 	      }
                   9144:               untie(%bighash)
1.481     raeburn  9145:            }
1.31      www      9146:         }
1.62      www      9147:         if ($syval) {
1.620     albertel 9148: 	    return $env{$cache_str}=$syval;
1.62      www      9149:         }
1.31      www      9150:     }
1.949     raeburn  9151:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9152:     return $env{$cache_str}='';
1.31      www      9153: }
                   9154: 
                   9155: # ---------------------------------------------------------- Return random seed
                   9156: 
1.32      www      9157: sub numval {
                   9158:     my $txt=shift;
                   9159:     $txt=~tr/A-J/0-9/;
                   9160:     $txt=~tr/a-j/0-9/;
                   9161:     $txt=~tr/K-T/0-9/;
                   9162:     $txt=~tr/k-t/0-9/;
                   9163:     $txt=~tr/U-Z/0-5/;
                   9164:     $txt=~tr/u-z/0-5/;
                   9165:     $txt=~s/\D//g;
1.564     albertel 9166:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9167:     return int($txt);
1.368     albertel 9168: }
                   9169: 
1.484     albertel 9170: sub numval2 {
                   9171:     my $txt=shift;
                   9172:     $txt=~tr/A-J/0-9/;
                   9173:     $txt=~tr/a-j/0-9/;
                   9174:     $txt=~tr/K-T/0-9/;
                   9175:     $txt=~tr/k-t/0-9/;
                   9176:     $txt=~tr/U-Z/0-5/;
                   9177:     $txt=~tr/u-z/0-5/;
                   9178:     $txt=~s/\D//g;
                   9179:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9180:     my $total;
                   9181:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9182:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9183:     return int($total);
                   9184: }
                   9185: 
1.575     albertel 9186: sub numval3 {
                   9187:     use integer;
                   9188:     my $txt=shift;
                   9189:     $txt=~tr/A-J/0-9/;
                   9190:     $txt=~tr/a-j/0-9/;
                   9191:     $txt=~tr/K-T/0-9/;
                   9192:     $txt=~tr/k-t/0-9/;
                   9193:     $txt=~tr/U-Z/0-5/;
                   9194:     $txt=~tr/u-z/0-5/;
                   9195:     $txt=~s/\D//g;
                   9196:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9197:     my $total;
                   9198:     foreach my $val (@txts) { $total+=$val; }
                   9199:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9200:     return $total;
                   9201: }
                   9202: 
1.675     albertel 9203: sub digest {
                   9204:     my ($data)=@_;
                   9205:     my $digest=&Digest::MD5::md5($data);
                   9206:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9207:     my ($e,$f);
                   9208:     {
                   9209:         use integer;
                   9210:         $e=($a+$b);
                   9211:         $f=($c+$d);
                   9212:         if ($_64bit) {
                   9213:             $e=(($e<<32)>>32);
                   9214:             $f=(($f<<32)>>32);
                   9215:         }
                   9216:     }
                   9217:     if (wantarray) {
                   9218: 	return ($e,$f);
                   9219:     } else {
                   9220: 	my $g;
                   9221: 	{
                   9222: 	    use integer;
                   9223: 	    $g=($e+$f);
                   9224: 	    if ($_64bit) {
                   9225: 		$g=(($g<<32)>>32);
                   9226: 	    }
                   9227: 	}
                   9228: 	return $g;
                   9229:     }
                   9230: }
                   9231: 
1.368     albertel 9232: sub latest_rnd_algorithm_id {
1.675     albertel 9233:     return '64bit5';
1.366     albertel 9234: }
1.32      www      9235: 
1.503     albertel 9236: sub get_rand_alg {
                   9237:     my ($courseid)=@_;
1.790     albertel 9238:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9239:     if ($courseid) {
1.620     albertel 9240: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9241:     }
                   9242:     return &latest_rnd_algorithm_id();
                   9243: }
                   9244: 
1.562     albertel 9245: sub validCODE {
                   9246:     my ($CODE)=@_;
                   9247:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9248:     return 0;
                   9249: }
                   9250: 
1.491     albertel 9251: sub getCODE {
1.620     albertel 9252:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9253:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9254: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9255: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9256: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9257:     }
                   9258:     return undef;
                   9259: }
                   9260: 
1.31      www      9261: sub rndseed {
1.155     albertel 9262:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9263:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9264:     if (!defined($symb)) {
1.366     albertel 9265: 	unless ($symb=$wsymb) { return time; }
                   9266:     }
                   9267:     if (!$courseid) { $courseid=$wcourseid; }
                   9268:     if (!$domain) { $domain=$wdomain; }
                   9269:     if (!$username) { $username=$wusername }
1.503     albertel 9270:     my $which=&get_rand_alg();
1.803     albertel 9271: 
1.491     albertel 9272:     if (defined(&getCODE())) {
1.675     albertel 9273: 	if ($which eq '64bit5') {
                   9274: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9275: 	} elsif ($which eq '64bit4') {
1.575     albertel 9276: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9277: 	} else {
                   9278: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9279: 	}
1.675     albertel 9280:     } elsif ($which eq '64bit5') {
                   9281: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9282:     } elsif ($which eq '64bit4') {
                   9283: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9284:     } elsif ($which eq '64bit3') {
                   9285: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9286:     } elsif ($which eq '64bit2') {
                   9287: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9288:     } elsif ($which eq '64bit') {
                   9289: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9290:     }
                   9291:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9292: }
                   9293: 
                   9294: sub rndseed_32bit {
                   9295:     my ($symb,$courseid,$domain,$username)=@_;
                   9296:     {
                   9297: 	use integer;
                   9298: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9299: 	my $symbseed=numval($symb) << 22;
                   9300: 	my $namechck=unpack("%32C*",$username) << 17;
                   9301: 	my $nameseed=numval($username) << 12;
                   9302: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9303: 	my $courseseed=unpack("%32C*",$courseid);
                   9304: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9305: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9306: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9307: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9308: 	return $num;
                   9309:     }
                   9310: }
                   9311: 
                   9312: sub rndseed_64bit {
                   9313:     my ($symb,$courseid,$domain,$username)=@_;
                   9314:     {
                   9315: 	use integer;
                   9316: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9317: 	my $symbseed=numval($symb) << 10;
                   9318: 	my $namechck=unpack("%32S*",$username);
                   9319: 	
                   9320: 	my $nameseed=numval($username) << 21;
                   9321: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9322: 	my $courseseed=unpack("%32S*",$courseid);
                   9323: 	
                   9324: 	my $num1=$symbchck+$symbseed+$namechck;
                   9325: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9326: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9327: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9328: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9329: 	return "$num1,$num2";
1.155     albertel 9330:     }
1.366     albertel 9331: }
                   9332: 
1.443     albertel 9333: sub rndseed_64bit2 {
                   9334:     my ($symb,$courseid,$domain,$username)=@_;
                   9335:     {
                   9336: 	use integer;
                   9337: 	# strings need to be an even # of cahracters long, it it is odd the
                   9338:         # last characters gets thrown away
                   9339: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9340: 	my $symbseed=numval($symb) << 10;
                   9341: 	my $namechck=unpack("%32S*",$username.' ');
                   9342: 	
                   9343: 	my $nameseed=numval($username) << 21;
1.501     albertel 9344: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9345: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9346: 	
                   9347: 	my $num1=$symbchck+$symbseed+$namechck;
                   9348: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9349: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9350: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9351: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9352: 	return "$num1,$num2";
                   9353:     }
                   9354: }
                   9355: 
                   9356: sub rndseed_64bit3 {
                   9357:     my ($symb,$courseid,$domain,$username)=@_;
                   9358:     {
                   9359: 	use integer;
                   9360: 	# strings need to be an even # of cahracters long, it it is odd the
                   9361:         # last characters gets thrown away
                   9362: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9363: 	my $symbseed=numval2($symb) << 10;
                   9364: 	my $namechck=unpack("%32S*",$username.' ');
                   9365: 	
                   9366: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9367: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9368: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9369: 	
                   9370: 	my $num1=$symbchck+$symbseed+$namechck;
                   9371: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9372: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9373: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9374: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9375: 	
1.503     albertel 9376: 	return "$num1:$num2";
1.443     albertel 9377:     }
                   9378: }
                   9379: 
1.575     albertel 9380: sub rndseed_64bit4 {
                   9381:     my ($symb,$courseid,$domain,$username)=@_;
                   9382:     {
                   9383: 	use integer;
                   9384: 	# strings need to be an even # of cahracters long, it it is odd the
                   9385:         # last characters gets thrown away
                   9386: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9387: 	my $symbseed=numval3($symb) << 10;
                   9388: 	my $namechck=unpack("%32S*",$username.' ');
                   9389: 	
                   9390: 	my $nameseed=numval3($username) << 21;
                   9391: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9392: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9393: 	
                   9394: 	my $num1=$symbchck+$symbseed+$namechck;
                   9395: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9396: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9397: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9398: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9399: 	
                   9400: 	return "$num1:$num2";
                   9401:     }
                   9402: }
                   9403: 
1.675     albertel 9404: sub rndseed_64bit5 {
                   9405:     my ($symb,$courseid,$domain,$username)=@_;
                   9406:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9407:     return "$num1:$num2";
                   9408: }
                   9409: 
1.366     albertel 9410: sub rndseed_CODE_64bit {
                   9411:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9412:     {
1.366     albertel 9413: 	use integer;
1.443     albertel 9414: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9415: 	my $symbseed=numval2($symb);
1.491     albertel 9416: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9417: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9418: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9419: 	my $num1=$symbseed+$CODEchck;
                   9420: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9421: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9422: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9423: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9424: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9425: 	return "$num1:$num2";
1.366     albertel 9426:     }
                   9427: }
                   9428: 
1.575     albertel 9429: sub rndseed_CODE_64bit4 {
                   9430:     my ($symb,$courseid,$domain,$username)=@_;
                   9431:     {
                   9432: 	use integer;
                   9433: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9434: 	my $symbseed=numval3($symb);
                   9435: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9436: 	my $CODEseed=numval3(&getCODE());
                   9437: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9438: 	my $num1=$symbseed+$CODEchck;
                   9439: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9440: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9441: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9442: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9443: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9444: 	return "$num1:$num2";
                   9445:     }
                   9446: }
                   9447: 
1.675     albertel 9448: sub rndseed_CODE_64bit5 {
                   9449:     my ($symb,$courseid,$domain,$username)=@_;
                   9450:     my $code = &getCODE();
                   9451:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9452:     return "$num1:$num2";
                   9453: }
                   9454: 
1.366     albertel 9455: sub setup_random_from_rndseed {
                   9456:     my ($rndseed)=@_;
1.503     albertel 9457:     if ($rndseed =~/([,:])/) {
                   9458: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9459: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9460:     } else {
                   9461: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9462:     }
1.36      albertel 9463: }
                   9464: 
1.474     albertel 9465: sub latest_receipt_algorithm_id {
1.835     albertel 9466:     return 'receipt3';
1.474     albertel 9467: }
                   9468: 
1.480     www      9469: sub recunique {
                   9470:     my $fucourseid=shift;
                   9471:     my $unique;
1.835     albertel 9472:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9473: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9474: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9475:     } else {
                   9476: 	$unique=$perlvar{'lonReceipt'};
                   9477:     }
                   9478:     return unpack("%32C*",$unique);
                   9479: }
                   9480: 
                   9481: sub recprefix {
                   9482:     my $fucourseid=shift;
                   9483:     my $prefix;
1.835     albertel 9484:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9485: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9486: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9487:     } else {
                   9488: 	$prefix=$perlvar{'lonHostID'};
                   9489:     }
                   9490:     return unpack("%32C*",$prefix);
                   9491: }
                   9492: 
1.76      www      9493: sub ireceipt {
1.474     albertel 9494:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9495: 
                   9496:     my $return =&recprefix($fucourseid).'-';
                   9497: 
                   9498:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9499: 	$env{'request.state'} eq 'construct') {
                   9500: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9501: 	return $return;
                   9502:     }
                   9503: 
1.76      www      9504:     my $cuname=unpack("%32C*",$funame);
                   9505:     my $cudom=unpack("%32C*",$fudom);
                   9506:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9507:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9508:     my $cunique=&recunique($fucourseid);
1.474     albertel 9509:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9510:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9511: 
1.790     albertel 9512: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9513: 			       
                   9514: 	$return.= ($cunique%$cuname+
                   9515: 		   $cunique%$cudom+
                   9516: 		   $cusymb%$cuname+
                   9517: 		   $cusymb%$cudom+
                   9518: 		   $cucourseid%$cuname+
                   9519: 		   $cucourseid%$cudom+
                   9520: 		   $cpart%$cuname+
                   9521: 		   $cpart%$cudom);
                   9522:     } else {
                   9523: 	$return.= ($cunique%$cuname+
                   9524: 		   $cunique%$cudom+
                   9525: 		   $cusymb%$cuname+
                   9526: 		   $cusymb%$cudom+
                   9527: 		   $cucourseid%$cuname+
                   9528: 		   $cucourseid%$cudom);
                   9529:     }
                   9530:     return $return;
1.76      www      9531: }
                   9532: 
                   9533: sub receipt {
1.474     albertel 9534:     my ($part)=@_;
1.790     albertel 9535:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9536:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9537: }
1.260     ng       9538: 
1.790     albertel 9539: sub whichuser {
                   9540:     my ($passedsymb)=@_;
                   9541:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9542:     if (defined($env{'form.grade_symb'})) {
                   9543: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9544: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9545: 	if (!$allowed &&
                   9546: 	    exists($env{'request.course.sec'}) &&
                   9547: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9548: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9549: 			      '/'.$env{'request.course.sec'});
                   9550: 	}
                   9551: 	if ($allowed) {
                   9552: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9553: 	    $courseid=$tmp_courseid;
                   9554: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9555: 	    ($name)=&get_env_multiple('form.grade_username');
                   9556: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9557: 	}
                   9558:     }
                   9559:     if (!$passedsymb) {
                   9560: 	$symb=&symbread();
                   9561:     } else {
                   9562: 	$symb=$passedsymb;
                   9563:     }
                   9564:     $courseid=$env{'request.course.id'};
                   9565:     $domain=$env{'user.domain'};
                   9566:     $name=$env{'user.name'};
                   9567:     if ($name eq 'public' && $domain eq 'public') {
                   9568: 	if (!defined($env{'form.username'})) {
                   9569: 	    $env{'form.username'}.=time.rand(10000000);
                   9570: 	}
                   9571: 	$name.=$env{'form.username'};
                   9572:     }
                   9573:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9574: 
                   9575: }
                   9576: 
1.36      albertel 9577: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9578: # returns either the contents of the file or 
                   9579: # -1 if the file doesn't exist
1.481     raeburn  9580: #
                   9581: # if the target is a file that was uploaded via DOCS, 
                   9582: # a check will be made to see if a current copy exists on the local server,
                   9583: # if it does this will be served, otherwise a copy will be retrieved from
                   9584: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9585: # the local server.   
1.472     albertel 9586: 
1.36      albertel 9587: sub getfile {
1.538     albertel 9588:     my ($file) = @_;
1.609     banghart 9589:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9590:     &repcopy($file);
                   9591:     return &readfile($file);
                   9592: }
                   9593: 
                   9594: sub repcopy_userfile {
                   9595:     my ($file)=@_;
1.609     banghart 9596:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9597:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9598:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9599: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9600:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9601:     if (-e "$file") {
1.828     www      9602: # we already have a local copy, check it out
1.538     albertel 9603: 	my @fileinfo = stat($file);
1.828     www      9604: 	my $rtncode;
                   9605: 	my $info;
1.538     albertel 9606: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9607: 	if ($lwpresp ne 'ok') {
1.828     www      9608: # there is no such file anymore, even though we had a local copy
1.482     albertel 9609: 	    if ($rtncode eq '404') {
1.538     albertel 9610: 		unlink($file);
1.482     albertel 9611: 	    }
                   9612: 	    return -1;
                   9613: 	}
                   9614: 	if ($info < $fileinfo[9]) {
1.828     www      9615: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9616: 	    return 'ok';
1.828     www      9617: 	} else {
                   9618: # the file is outdated, get rid of it
                   9619: 	    unlink($file);
1.482     albertel 9620: 	}
1.828     www      9621:     }
                   9622: # one way or the other, at this point, we don't have the file
                   9623: # construct the correct path for the file
                   9624:     my @parts = ($cdom,$cnum); 
                   9625:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9626: 	push @parts, split(/\//,$1);
                   9627:     }
                   9628:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9629:     foreach my $part (@parts) {
                   9630: 	$path .= '/'.$part;
                   9631: 	if (!-e $path) {
                   9632: 	    mkdir($path,0770);
1.482     albertel 9633: 	}
                   9634:     }
1.828     www      9635: # now the path exists for sure
                   9636: # get a user agent
                   9637:     my $ua=new LWP::UserAgent;
                   9638:     my $transferfile=$file.'.in.transfer';
                   9639: # FIXME: this should flock
                   9640:     if (-e $transferfile) { return 'ok'; }
                   9641:     my $request;
                   9642:     $uri=~s/^\///;
1.980     raeburn  9643:     my $homeserver = &homeserver($cnum,$cdom);
                   9644:     my $protocol = $protocol{$homeserver};
                   9645:     $protocol = 'http' if ($protocol ne 'https');
                   9646:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9647:     my $response=$ua->request($request,$transferfile);
                   9648: # did it work?
                   9649:     if ($response->is_error()) {
                   9650: 	unlink($transferfile);
                   9651: 	&logthis("Userfile repcopy failed for $uri");
                   9652: 	return -1;
                   9653:     }
                   9654: # worked, rename the transfer file
                   9655:     rename($transferfile,$file);
1.607     raeburn  9656:     return 'ok';
1.481     raeburn  9657: }
                   9658: 
1.517     albertel 9659: sub tokenwrapper {
                   9660:     my $uri=shift;
1.980     raeburn  9661:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9662:     $uri=~s|^/||;
1.620     albertel 9663:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9664:     my $token=$1;
1.552     albertel 9665:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9666:     if ($udom && $uname && $file) {
                   9667: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9668:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9669:         my $homeserver = &homeserver($uname,$udom);
                   9670:         my $protocol = $protocol{$homeserver};
                   9671:         $protocol = 'http' if ($protocol ne 'https');
                   9672:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9673:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9674:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9675:     } else {
                   9676:         return '/adm/notfound.html';
                   9677:     }
                   9678: }
                   9679: 
1.828     www      9680: # call with reqtype HEAD: get last modification time
                   9681: # call with reqtype GET: get the file contents
                   9682: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9683: #
1.481     raeburn  9684: sub getuploaded {
                   9685:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9686:     $uri=~s/^\///;
1.980     raeburn  9687:     my $homeserver = &homeserver($cnum,$cdom);
                   9688:     my $protocol = $protocol{$homeserver};
                   9689:     $protocol = 'http' if ($protocol ne 'https');
                   9690:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9691:     my $ua=new LWP::UserAgent;
                   9692:     my $request=new HTTP::Request($reqtype,$uri);
                   9693:     my $response=$ua->request($request);
                   9694:     $$rtncode = $response->code;
1.482     albertel 9695:     if (! $response->is_success()) {
                   9696: 	return 'failed';
                   9697:     }      
                   9698:     if ($reqtype eq 'HEAD') {
1.486     www      9699: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9700:     } elsif ($reqtype eq 'GET') {
                   9701: 	$$info = $response->content;
1.472     albertel 9702:     }
1.482     albertel 9703:     return 'ok';
1.36      albertel 9704: }
                   9705: 
1.481     raeburn  9706: sub readfile {
                   9707:     my $file = shift;
                   9708:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9709:     my $fh;
                   9710:     open($fh,"<$file");
                   9711:     my $a='';
1.800     albertel 9712:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9713:     return $a;
                   9714: }
                   9715: 
1.36      albertel 9716: sub filelocation {
1.590     banghart 9717:     my ($dir,$file) = @_;
                   9718:     my $location;
                   9719:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9720: 
                   9721:     if ($file =~ m-^/adm/-) {
                   9722: 	$file=~s-^/adm/wrapper/-/-;
                   9723: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9724:     }
1.882     albertel 9725: 
1.590     banghart 9726:     if ($file=~m:^/~:) { # is a contruction space reference
                   9727:         $location = $file;
                   9728:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9729:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9730: 	# is a correct contruction space reference
                   9731:         $location = $file;
1.956     raeburn  9732:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9733:         $location = $file;
1.609     banghart 9734:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9735:         my ($udom,$uname,$filename)=
1.811     albertel 9736:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9737:         my $home=&homeserver($uname,$udom);
                   9738:         my $is_me=0;
                   9739:         my @ids=&current_machine_ids();
                   9740:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9741:         if ($is_me) {
1.955     raeburn  9742:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9743:         } else {
                   9744:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9745:   	      $udom.'/'.$uname.'/'.$filename;
                   9746:         }
1.882     albertel 9747:     } elsif ($file =~ m-^/adm/-) {
                   9748: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9749:     } else {
                   9750:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9751:         $file=~s:^/res/:/:;
                   9752:         if ( !( $file =~ m:^/:) ) {
                   9753:             $location = $dir. '/'.$file;
                   9754:         } else {
                   9755:             $location = '/home/httpd/html/res'.$file;
                   9756:         }
1.59      albertel 9757:     }
1.590     banghart 9758:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9759:     while ($location=~m{/\.\./}) {
                   9760: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9761: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9762: 	} else {
                   9763: 	    $location=~ s{/\.\./}{/}g;
                   9764: 	}
                   9765:     } #remove dir/..
1.590     banghart 9766:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9767:     return $location;
1.46      www      9768: }
1.36      albertel 9769: 
1.46      www      9770: sub hreflocation {
                   9771:     my ($dir,$file)=@_;
1.980     raeburn  9772:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9773: 	$file=filelocation($dir,$file);
1.700     albertel 9774:     } elsif ($file=~m-^/adm/-) {
                   9775: 	$file=~s-^/adm/wrapper/-/-;
                   9776: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9777:     }
                   9778:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9779: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9780:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9781: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9782:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9783: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9784: 	    -/uploaded/$1/$2/-x;
1.46      www      9785:     }
1.913     albertel 9786:     if ($file=~ m{^/userfiles/}) {
                   9787: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9788:     }
1.462     albertel 9789:     return $file;
1.465     albertel 9790: }
                   9791: 
                   9792: sub current_machine_domains {
1.853     albertel 9793:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9794: }
                   9795: 
                   9796: sub machine_domains {
                   9797:     my ($hostname) = @_;
1.465     albertel 9798:     my @domains;
1.838     albertel 9799:     my %hostname = &all_hostnames();
1.465     albertel 9800:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9801: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9802: 	if ($hostname eq $name) {
1.844     albertel 9803: 	    push(@domains,&host_domain($id));
1.465     albertel 9804: 	}
                   9805:     }
                   9806:     return @domains;
                   9807: }
                   9808: 
                   9809: sub current_machine_ids {
1.853     albertel 9810:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9811: }
                   9812: 
                   9813: sub machine_ids {
                   9814:     my ($hostname) = @_;
                   9815:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9816:     my @ids;
1.888     albertel 9817:     my %name_to_host = &all_names();
1.889     albertel 9818:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9819: 	return @{ $name_to_host{$hostname} };
                   9820:     }
                   9821:     return;
1.31      www      9822: }
                   9823: 
1.824     raeburn  9824: sub additional_machine_domains {
                   9825:     my @domains;
                   9826:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9827:     while( my $line = <$fh>) {
                   9828:         $line =~ s/\s//g;
                   9829:         push(@domains,$line);
                   9830:     }
                   9831:     return @domains;
                   9832: }
                   9833: 
                   9834: sub default_login_domain {
                   9835:     my $domain = $perlvar{'lonDefDomain'};
                   9836:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9837:     foreach my $posdom (&current_machine_domains(),
                   9838:                         &additional_machine_domains()) {
                   9839:         if (lc($posdom) eq lc($testdomain)) {
                   9840:             $domain=$posdom;
                   9841:             last;
                   9842:         }
                   9843:     }
                   9844:     return $domain;
                   9845: }
                   9846: 
1.31      www      9847: # ------------------------------------------------------------- Declutters URLs
                   9848: 
                   9849: sub declutter {
                   9850:     my $thisfn=shift;
1.569     albertel 9851:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9852:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9853:     $thisfn=~s/^\///;
1.697     albertel 9854:     $thisfn=~s|^adm/wrapper/||;
                   9855:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9856:     $thisfn=~s/^res\///;
1.1032    raeburn  9857:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9858:         $thisfn=~s/\?.+$//;
                   9859:     }
1.268     www      9860:     return $thisfn;
                   9861: }
                   9862: 
                   9863: # ------------------------------------------------------------- Clutter up URLs
                   9864: 
                   9865: sub clutter {
                   9866:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9867:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9868: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9869:        $thisfn='/res'.$thisfn; 
                   9870:     }
1.1031    raeburn  9871:     if ($thisfn !~m|^/adm|) {
                   9872: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9873: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9874: 	} else {
                   9875: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9876: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9877: 	    if ($embstyle eq 'ssi'
                   9878: 		|| ($embstyle eq 'hdn')
                   9879: 		|| ($embstyle eq 'rat')
                   9880: 		|| ($embstyle eq 'prv')
                   9881: 		|| ($embstyle eq 'ign')) {
                   9882: 		#do nothing with these
                   9883: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9884: 		|| ($embstyle eq 'emb')
                   9885: 		|| ($embstyle eq 'wrp')) {
                   9886: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9887: 	    } elsif ($embstyle eq 'unk'
                   9888: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9889: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9890: 	    } else {
1.718     www      9891: #		&logthis("Got a blank emb style");
1.695     albertel 9892: 	    }
1.694     albertel 9893: 	}
                   9894:     }
1.31      www      9895:     return $thisfn;
1.12      www      9896: }
                   9897: 
1.787     albertel 9898: sub clutter_with_no_wrapper {
                   9899:     my $uri = &clutter(shift);
                   9900:     if ($uri =~ m-^/adm/-) {
                   9901: 	$uri =~ s-^/adm/wrapper/-/-;
                   9902: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9903:     }
                   9904:     return $uri;
                   9905: }
                   9906: 
1.557     albertel 9907: sub freeze_escape {
                   9908:     my ($value)=@_;
                   9909:     if (ref($value)) {
                   9910: 	$value=&nfreeze($value);
                   9911: 	return '__FROZEN__'.&escape($value);
                   9912:     }
                   9913:     return &escape($value);
                   9914: }
                   9915: 
1.11      www      9916: 
1.557     albertel 9917: sub thaw_unescape {
                   9918:     my ($value)=@_;
                   9919:     if ($value =~ /^__FROZEN__/) {
                   9920: 	substr($value,0,10,undef);
                   9921: 	$value=&unescape($value);
                   9922: 	return &thaw($value);
                   9923:     }
                   9924:     return &unescape($value);
                   9925: }
                   9926: 
1.436     albertel 9927: sub correct_line_ends {
                   9928:     my ($result)=@_;
                   9929:     $$result =~s/\r\n/\n/mg;
                   9930:     $$result =~s/\r/\n/mg;
1.415     albertel 9931: }
1.1       albertel 9932: # ================================================================ Main Program
                   9933: 
1.184     www      9934: sub goodbye {
1.204     albertel 9935:    &logthis("Starting Shut down");
1.443     albertel 9936: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9937:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9938: #converted
1.599     albertel 9939: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9940:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9941: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9942: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9943: #1.1 only
1.870     albertel 9944: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9945: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9946: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9947: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9948:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9949:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9950:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9951:    &flushcourselogs();
                   9952:    &logthis("Shutting down");
                   9953: }
                   9954: 
1.852     albertel 9955: sub get_dns {
1.869     albertel 9956:     my ($url,$func,$ignore_cache) = @_;
                   9957:     if (!$ignore_cache) {
                   9958: 	my ($content,$cached)=
                   9959: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9960: 	if ($cached) {
                   9961: 	    &$func($content);
                   9962: 	    return;
                   9963: 	}
                   9964:     }
                   9965: 
                   9966:     my %alldns;
1.852     albertel 9967:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9968:     foreach my $dns (<$config>) {
                   9969: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9970:         my $line = $1;
                   9971:         my ($host,$protocol) = split(/:/,$line);
                   9972:         if ($protocol ne 'https') {
                   9973:             $protocol = 'http';
                   9974:         }
                   9975: 	$alldns{$host} = $protocol;
1.869     albertel 9976:     }
                   9977:     while (%alldns) {
                   9978: 	my ($dns) = keys(%alldns);
1.852     albertel 9979: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9980: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9981: 	my $response=$ua->request($request);
1.979     raeburn  9982:         delete($alldns{$dns});
1.852     albertel 9983: 	next if ($response->is_error());
                   9984: 	my @content = split("\n",$response->content);
1.869     albertel 9985: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9986: 	&$func(\@content);
1.869     albertel 9987: 	return;
1.852     albertel 9988:     }
                   9989:     close($config);
1.871     albertel 9990:     my $which = (split('/',$url))[3];
                   9991:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9992:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9993:     my @content = <$config>;
                   9994:     &$func(\@content);
                   9995:     return;
1.852     albertel 9996: }
1.327     albertel 9997: # ------------------------------------------------------------ Read domain file
                   9998: {
1.852     albertel 9999:     my $loaded;
1.846     albertel 10000:     my %domain;
                   10001: 
1.852     albertel 10002:     sub parse_domain_tab {
                   10003: 	my ($lines) = @_;
                   10004: 	foreach my $line (@$lines) {
                   10005: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10006: 
1.846     albertel 10007: 	    chomp($line);
1.852     albertel 10008: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10009: 	    my %this_domain;
                   10010: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10011: 			       'lang_def', 'city', 'longi', 'lati',
                   10012: 			       'primary') {
                   10013: 		$this_domain{$field} = shift(@elements);
                   10014: 	    }
                   10015: 	    $domain{$name} = \%this_domain;
1.852     albertel 10016: 	}
                   10017:     }
1.864     albertel 10018: 
                   10019:     sub reset_domain_info {
                   10020: 	undef($loaded);
                   10021: 	undef(%domain);
                   10022:     }
                   10023: 
1.852     albertel 10024:     sub load_domain_tab {
1.869     albertel 10025: 	my ($ignore_cache) = @_;
                   10026: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10027: 	my $fh;
                   10028: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10029: 	    my @lines = <$fh>;
                   10030: 	    &parse_domain_tab(\@lines);
1.448     albertel 10031: 	}
1.852     albertel 10032: 	close($fh);
                   10033: 	$loaded = 1;
1.327     albertel 10034:     }
1.846     albertel 10035: 
                   10036:     sub domain {
1.852     albertel 10037: 	&load_domain_tab() if (!$loaded);
                   10038: 
1.846     albertel 10039: 	my ($name,$what) = @_;
                   10040: 	return if ( !exists($domain{$name}) );
                   10041: 
                   10042: 	if (!$what) {
                   10043: 	    return $domain{$name}{'description'};
                   10044: 	}
                   10045: 	return $domain{$name}{$what};
                   10046:     }
1.974     raeburn  10047: 
                   10048:     sub domain_info {
                   10049:         &load_domain_tab() if (!$loaded);
                   10050:         return %domain;
                   10051:     }
                   10052: 
1.327     albertel 10053: }
                   10054: 
                   10055: 
1.1       albertel 10056: # ------------------------------------------------------------- Read hosts file
                   10057: {
1.838     albertel 10058:     my %hostname;
1.844     albertel 10059:     my %hostdom;
1.845     albertel 10060:     my %libserv;
1.852     albertel 10061:     my $loaded;
1.888     albertel 10062:     my %name_to_host;
1.1074    raeburn  10063:     my %internetdom;
1.852     albertel 10064: 
                   10065:     sub parse_hosts_tab {
                   10066: 	my ($file) = @_;
                   10067: 	foreach my $configline (@$file) {
                   10068: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10069: 	    next if ($configline =~ /^\^/);
                   10070: 	    chomp($configline);
1.1074    raeburn  10071: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10072: 	    $name=~s/\s//g;
                   10073: 	    if ($id && $domain && $role && $name) {
                   10074: 		$hostname{$id}=$name;
1.888     albertel 10075: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10076: 		$hostdom{$id}=$domain;
                   10077: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10078:                 if (defined($protocol)) {
                   10079:                     if ($protocol eq 'https') {
                   10080:                         $protocol{$id} = $protocol;
                   10081:                     } else {
                   10082:                         $protocol{$id} = 'http'; 
                   10083:                     }
1.968     raeburn  10084:                 } else {
1.969     raeburn  10085:                     $protocol{$id} = 'http';
1.968     raeburn  10086:                 }
1.1074    raeburn  10087:                 if (defined($intdom)) {
                   10088:                     $internetdom{$id} = $intdom;
                   10089:                 }
1.852     albertel 10090: 	    }
                   10091: 	}
                   10092:     }
1.864     albertel 10093:     
                   10094:     sub reset_hosts_info {
1.897     albertel 10095: 	&purge_remembered();
1.864     albertel 10096: 	&reset_domain_info();
                   10097: 	&reset_hosts_ip_info();
1.892     albertel 10098: 	undef(%name_to_host);
1.864     albertel 10099: 	undef(%hostname);
                   10100: 	undef(%hostdom);
                   10101: 	undef(%libserv);
                   10102: 	undef($loaded);
                   10103:     }
1.1       albertel 10104: 
1.852     albertel 10105:     sub load_hosts_tab {
1.869     albertel 10106: 	my ($ignore_cache) = @_;
                   10107: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10108: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10109: 	my @config = <$config>;
                   10110: 	&parse_hosts_tab(\@config);
                   10111: 	close($config);
                   10112: 	$loaded=1;
1.1       albertel 10113:     }
1.852     albertel 10114: 
1.838     albertel 10115:     sub hostname {
1.852     albertel 10116: 	&load_hosts_tab() if (!$loaded);
                   10117: 
1.838     albertel 10118: 	my ($lonid) = @_;
                   10119: 	return $hostname{$lonid};
                   10120:     }
1.845     albertel 10121: 
1.838     albertel 10122:     sub all_hostnames {
1.852     albertel 10123: 	&load_hosts_tab() if (!$loaded);
                   10124: 
1.838     albertel 10125: 	return %hostname;
                   10126:     }
1.845     albertel 10127: 
1.888     albertel 10128:     sub all_names {
                   10129: 	&load_hosts_tab() if (!$loaded);
                   10130: 
                   10131: 	return %name_to_host;
                   10132:     }
                   10133: 
1.974     raeburn  10134:     sub all_host_domain {
                   10135:         &load_hosts_tab() if (!$loaded);
                   10136:         return %hostdom;
                   10137:     }
                   10138: 
1.845     albertel 10139:     sub is_library {
1.852     albertel 10140: 	&load_hosts_tab() if (!$loaded);
                   10141: 
1.845     albertel 10142: 	return exists($libserv{$_[0]});
                   10143:     }
                   10144: 
                   10145:     sub all_library {
1.852     albertel 10146: 	&load_hosts_tab() if (!$loaded);
                   10147: 
1.845     albertel 10148: 	return %libserv;
                   10149:     }
                   10150: 
1.1062    droeschl 10151:     sub unique_library {
                   10152: 	#2x reverse removes all hostnames that appear more than once
                   10153:         my %unique = reverse &all_library();
                   10154:         return reverse %unique;
                   10155:     }
                   10156: 
1.841     albertel 10157:     sub get_servers {
1.852     albertel 10158: 	&load_hosts_tab() if (!$loaded);
                   10159: 
1.841     albertel 10160: 	my ($domain,$type) = @_;
                   10161: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10162: 	                                          : %hostname;
                   10163: 	my %result;
1.842     albertel 10164: 	if (ref($domain) eq 'ARRAY') {
                   10165: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10166: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10167: 		    $result{$host} = $hostname;
                   10168: 		}
                   10169: 	    }
                   10170: 	} else {
                   10171: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10172: 		if ($hostdom{$host} eq $domain) {
                   10173: 		    $result{$host} = $hostname;
                   10174: 		}
1.841     albertel 10175: 	    }
                   10176: 	}
                   10177: 	return %result;
                   10178:     }
1.845     albertel 10179: 
1.1062    droeschl 10180:     sub get_unique_servers {
                   10181:         my %unique = reverse &get_servers(@_);
                   10182: 	return reverse %unique;
                   10183:     }
                   10184: 
1.844     albertel 10185:     sub host_domain {
1.852     albertel 10186: 	&load_hosts_tab() if (!$loaded);
                   10187: 
1.844     albertel 10188: 	my ($lonid) = @_;
                   10189: 	return $hostdom{$lonid};
                   10190:     }
                   10191: 
1.841     albertel 10192:     sub all_domains {
1.852     albertel 10193: 	&load_hosts_tab() if (!$loaded);
                   10194: 
1.841     albertel 10195: 	my %seen;
                   10196: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10197: 	return @uniq;
                   10198:     }
1.1074    raeburn  10199: 
                   10200:     sub internet_dom {
                   10201:         &load_hosts_tab() if (!$loaded);
                   10202: 
                   10203:         my ($lonid) = @_;
                   10204:         return $internetdom{$lonid};
                   10205:     }
1.1       albertel 10206: }
                   10207: 
1.847     albertel 10208: { 
                   10209:     my %iphost;
1.856     albertel 10210:     my %name_to_ip;
                   10211:     my %lonid_to_ip;
1.869     albertel 10212: 
1.847     albertel 10213:     sub get_hosts_from_ip {
                   10214: 	my ($ip) = @_;
                   10215: 	my %iphosts = &get_iphost();
                   10216: 	if (ref($iphosts{$ip})) {
                   10217: 	    return @{$iphosts{$ip}};
                   10218: 	}
                   10219: 	return;
1.839     albertel 10220:     }
1.864     albertel 10221:     
                   10222:     sub reset_hosts_ip_info {
                   10223: 	undef(%iphost);
                   10224: 	undef(%name_to_ip);
                   10225: 	undef(%lonid_to_ip);
                   10226:     }
1.856     albertel 10227: 
                   10228:     sub get_host_ip {
                   10229: 	my ($lonid) = @_;
                   10230: 	if (exists($lonid_to_ip{$lonid})) {
                   10231: 	    return $lonid_to_ip{$lonid};
                   10232: 	}
                   10233: 	my $name=&hostname($lonid);
                   10234:    	my $ip = gethostbyname($name);
                   10235: 	return if (!$ip || length($ip) ne 4);
                   10236: 	$ip=inet_ntoa($ip);
                   10237: 	$name_to_ip{$name}   = $ip;
                   10238: 	$lonid_to_ip{$lonid} = $ip;
                   10239: 	return $ip;
                   10240:     }
1.847     albertel 10241:     
                   10242:     sub get_iphost {
1.869     albertel 10243: 	my ($ignore_cache) = @_;
1.894     albertel 10244: 
1.869     albertel 10245: 	if (!$ignore_cache) {
                   10246: 	    if (%iphost) {
                   10247: 		return %iphost;
                   10248: 	    }
                   10249: 	    my ($ip_info,$cached)=
                   10250: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10251: 	    if ($cached) {
                   10252: 		%iphost      = %{$ip_info->[0]};
                   10253: 		%name_to_ip  = %{$ip_info->[1]};
                   10254: 		%lonid_to_ip = %{$ip_info->[2]};
                   10255: 		return %iphost;
                   10256: 	    }
                   10257: 	}
1.894     albertel 10258: 
                   10259: 	# get yesterday's info for fallback
                   10260: 	my %old_name_to_ip;
                   10261: 	my ($ip_info,$cached)=
                   10262: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10263: 	if ($cached) {
                   10264: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10265: 	}
                   10266: 
1.888     albertel 10267: 	my %name_to_host = &all_names();
                   10268: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10269: 	    my $ip;
                   10270: 	    if (!exists($name_to_ip{$name})) {
                   10271: 		$ip = gethostbyname($name);
                   10272: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10273: 		    if (defined($old_name_to_ip{$name})) {
                   10274: 			$ip = $old_name_to_ip{$name};
                   10275: 			&logthis("Can't find $name defaulting to old $ip");
                   10276: 		    } else {
                   10277: 			&logthis("Name $name no IP found");
                   10278: 			next;
                   10279: 		    }
                   10280: 		} else {
                   10281: 		    $ip=inet_ntoa($ip);
1.847     albertel 10282: 		}
                   10283: 		$name_to_ip{$name} = $ip;
                   10284: 	    } else {
                   10285: 		$ip = $name_to_ip{$name};
1.653     albertel 10286: 	    }
1.888     albertel 10287: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10288: 		$lonid_to_ip{$id} = $ip;
                   10289: 	    }
                   10290: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10291: 	}
1.869     albertel 10292: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10293: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10294: 				      48*60*60);
1.869     albertel 10295: 
1.847     albertel 10296: 	return %iphost;
1.598     albertel 10297:     }
                   10298: 
1.992     raeburn  10299:     #
                   10300:     #  Given a DNS returns the loncapa host name for that DNS 
                   10301:     # 
                   10302:     sub host_from_dns {
                   10303:         my ($dns) = @_;
                   10304:         my @hosts;
                   10305:         my $ip;
                   10306: 
1.993     raeburn  10307:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10308:             $ip = $name_to_ip{$dns};
                   10309:         }
                   10310:         if (!$ip) {
                   10311:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10312:             if (length($ip) == 4) { 
                   10313: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10314:             }
                   10315:         }
                   10316:         if ($ip) {
                   10317: 	    @hosts = get_hosts_from_ip($ip);
                   10318: 	    return $hosts[0];
                   10319:         }
                   10320:         return undef;
1.986     foxr     10321:     }
1.992     raeburn  10322: 
1.1074    raeburn  10323:     sub get_internet_names {
                   10324:         my ($lonid) = @_;
                   10325:         return if ($lonid eq '');
                   10326:         my ($idnref,$cached)=
                   10327:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10328:         if ($cached) {
                   10329:             return $idnref;
                   10330:         }
                   10331:         my $ip = &get_host_ip($lonid);
                   10332:         my @hosts = &get_hosts_from_ip($ip);
                   10333:         my %iphost = &get_iphost();
                   10334:         my (@idns,%seen);
                   10335:         foreach my $id (@hosts) {
                   10336:             my $dom = &host_domain($id);
                   10337:             my $prim_id = &domain($dom,'primary');
                   10338:             my $prim_ip = &get_host_ip($prim_id);
                   10339:             next if ($seen{$prim_ip});
                   10340:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10341:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10342:                     my $intdom = &internet_dom($id);
                   10343:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10344:                         push(@idns,$intdom);
                   10345:                     }
                   10346:                 }
                   10347:             }
                   10348:             $seen{$prim_ip} = 1;
                   10349:         }
                   10350:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10351:     }
                   10352: 
1.986     foxr     10353: }
                   10354: 
1.1079    raeburn  10355: sub all_loncaparevs {
                   10356:     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);
                   10357: }
                   10358: 
1.862     albertel 10359: BEGIN {
                   10360: 
                   10361: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10362:     unless ($readit) {
                   10363: {
                   10364:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10365:     %perlvar = (%perlvar,%{$configvars});
                   10366: }
                   10367: 
                   10368: 
1.1       albertel 10369: # ------------------------------------------------------ Read spare server file
                   10370: {
1.448     albertel 10371:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10372: 
                   10373:     while (my $configline=<$config>) {
                   10374:        chomp($configline);
1.284     matthew  10375:        if ($configline) {
1.784     albertel 10376: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10377: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10378: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10379:        }
                   10380:     }
1.448     albertel 10381:     close($config);
1.1       albertel 10382: }
1.11      www      10383: # ------------------------------------------------------------ Read permissions
                   10384: {
1.448     albertel 10385:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10386: 
                   10387:     while (my $configline=<$config>) {
1.448     albertel 10388: 	chomp($configline);
                   10389: 	if ($configline) {
                   10390: 	    my ($role,$perm)=split(/ /,$configline);
                   10391: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10392: 	}
1.11      www      10393:     }
1.448     albertel 10394:     close($config);
1.11      www      10395: }
                   10396: 
                   10397: # -------------------------------------------- Read plain texts for permissions
                   10398: {
1.448     albertel 10399:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10400: 
                   10401:     while (my $configline=<$config>) {
1.448     albertel 10402: 	chomp($configline);
                   10403: 	if ($configline) {
1.742     raeburn  10404: 	    my ($short,@plain)=split(/:/,$configline);
                   10405:             %{$prp{$short}} = ();
                   10406: 	    if (@plain > 0) {
                   10407:                 $prp{$short}{'std'} = $plain[0];
                   10408:                 for (my $i=1; $i<@plain; $i++) {
                   10409:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10410:                 }
                   10411:             }
1.448     albertel 10412: 	}
1.135     www      10413:     }
1.448     albertel 10414:     close($config);
1.135     www      10415: }
                   10416: 
                   10417: # ---------------------------------------------------------- Read package table
                   10418: {
1.448     albertel 10419:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10420: 
                   10421:     while (my $configline=<$config>) {
1.483     albertel 10422: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10423: 	chomp($configline);
                   10424: 	my ($short,$plain)=split(/:/,$configline);
                   10425: 	my ($pack,$name)=split(/\&/,$short);
                   10426: 	if ($plain ne '') {
                   10427: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10428: 	    $packagetab{$short}=$plain; 
                   10429: 	}
1.11      www      10430:     }
1.448     albertel 10431:     close($config);
1.329     matthew  10432: }
                   10433: 
1.1073    raeburn  10434: # ---------------------------------------------------------- Read loncaparev table
                   10435: {
                   10436:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10437:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10438:             while (my $configline=<$config>) {
                   10439:                 chomp($configline);
                   10440:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10441:                 $loncaparevs{$hostid}=$loncaparev;
                   10442:             }
                   10443:             close($config);
                   10444:         }
                   10445:     }
                   10446: }
                   10447: 
1.1074    raeburn  10448: # ---------------------------------------------------------- Read serverhostID table
                   10449: {
                   10450:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10451:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10452:             while (my $configline=<$config>) {
                   10453:                 chomp($configline);
                   10454:                 my ($name,$id)=split(/:/,$configline);
                   10455:                 $serverhomeIDs{$name}=$id;
                   10456:             }
                   10457:             close($config);
                   10458:         }
                   10459:     }
                   10460: }
                   10461: 
1.1079    raeburn  10462: {
                   10463:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10464:     if (-e $file) {
                   10465:         my $parser = HTML::LCParser->new($file);
                   10466:         while (my $token = $parser->get_token()) {
                   10467:             if ($token->[0] eq 'S') {
                   10468:                 my $item = $token->[1];
                   10469:                 my $name = $token->[2]{'name'};
                   10470:                 my $value = $token->[2]{'value'};
                   10471:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10472:                     my $release = $parser->get_text();
                   10473:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10474:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10475:                 }
                   10476:             }
                   10477:         }
                   10478:     }
1.1073    raeburn  10479: }
                   10480: 
1.329     matthew  10481: # ------------- set up temporary directory
                   10482: {
                   10483:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10484: 
1.11      www      10485: }
                   10486: 
1.794     albertel 10487: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10488: 				'compress_threshold'=> 20_000,
                   10489:  			        });
1.185     www      10490: 
1.281     www      10491: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10492: $dumpcount=0;
1.958     www      10493: $locknum=0;
1.22      www      10494: 
1.163     harris41 10495: &logtouch();
1.672     albertel 10496: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10497: $readit=1;
1.564     albertel 10498:     {
                   10499: 	use integer;
                   10500: 	my $test=(2**32)+1;
1.568     albertel 10501: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10502: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10503:     }
1.195     www      10504: }
1.1       albertel 10505: }
1.179     www      10506: 
1.1       albertel 10507: 1;
1.191     harris41 10508: __END__
                   10509: 
1.243     albertel 10510: =pod
                   10511: 
1.191     harris41 10512: =head1 NAME
                   10513: 
1.243     albertel 10514: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10515: 
                   10516: =head1 SYNOPSIS
                   10517: 
1.243     albertel 10518: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10519: 
                   10520:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10521: 
1.243     albertel 10522: Common parameters:
                   10523: 
                   10524: =over 4
                   10525: 
                   10526: =item *
                   10527: 
                   10528: $uname : an internal username (if $cname expecting a course Id specifically)
                   10529: 
                   10530: =item *
                   10531: 
                   10532: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10533: 
                   10534: =item *
                   10535: 
                   10536: $symb : a resource instance identifier
                   10537: 
                   10538: =item *
                   10539: 
                   10540: $namespace : the name of a .db file that contains the data needed or
                   10541: being set.
                   10542: 
                   10543: =back
                   10544: 
1.394     bowersj2 10545: =head1 OVERVIEW
1.191     harris41 10546: 
1.394     bowersj2 10547: lonnet provides subroutines which interact with the
                   10548: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10549: about classes, users, and resources.
1.243     albertel 10550: 
                   10551: For many of these objects you can also use this to store data about
                   10552: them or modify them in various ways.
1.191     harris41 10553: 
1.394     bowersj2 10554: =head2 Symbs
1.191     harris41 10555: 
1.394     bowersj2 10556: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10557: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10558: map, the resource number of the resource in the map, and the URL of
                   10559: the resource itself. The latter is somewhat redundant, but might help
                   10560: if maps change.
                   10561: 
                   10562: An example is
                   10563: 
                   10564:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10565: 
                   10566: The respective map entry is
                   10567: 
                   10568:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10569:   title="Problem 2">
                   10570:  </resource>
                   10571: 
                   10572: Symbs are used by the random number generator, as well as to store and
                   10573: restore data specific to a certain instance of for example a problem.
                   10574: 
                   10575: =head2 Storing And Retrieving Data
                   10576: 
                   10577: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10578: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10579: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10580: is is the non-critical message twin of cstore. These functions are for
                   10581: handlers to store a perl hash to a user's permanent data space in an
                   10582: easy manner, and to retrieve it again on another call. It is expected
                   10583: that a handler would use this once at the beginning to retrieve data,
                   10584: and then again once at the end to send only the new data back.
                   10585: 
                   10586: The data is stored in the user's data directory on the user's
                   10587: homeserver under the ID of the course.
                   10588: 
                   10589: The hash that is returned by restore will have all of the previous
                   10590: value for all of the elements of the hash.
                   10591: 
                   10592: Example:
                   10593: 
                   10594:  #creating a hash
                   10595:  my %hash;
                   10596:  $hash{'foo'}='bar';
                   10597: 
                   10598:  #storing it
                   10599:  &Apache::lonnet::cstore(\%hash);
                   10600: 
                   10601:  #changing a value
                   10602:  $hash{'foo'}='notbar';
                   10603: 
                   10604:  #adding a new value
                   10605:  $hash{'bar'}='foo';
                   10606:  &Apache::lonnet::cstore(\%hash);
                   10607: 
                   10608:  #retrieving the hash
                   10609:  my %history=&Apache::lonnet::restore();
                   10610: 
                   10611:  #print the hash
                   10612:  foreach my $key (sort(keys(%history))) {
                   10613:    print("\%history{$key} = $history{$key}");
                   10614:  }
                   10615: 
                   10616: Will print out:
1.191     harris41 10617: 
1.394     bowersj2 10618:  %history{1:foo} = bar
                   10619:  %history{1:keys} = foo:timestamp
                   10620:  %history{1:timestamp} = 990455579
                   10621:  %history{2:bar} = foo
                   10622:  %history{2:foo} = notbar
                   10623:  %history{2:keys} = foo:bar:timestamp
                   10624:  %history{2:timestamp} = 990455580
                   10625:  %history{bar} = foo
                   10626:  %history{foo} = notbar
                   10627:  %history{timestamp} = 990455580
                   10628:  %history{version} = 2
                   10629: 
                   10630: Note that the special hash entries C<keys>, C<version> and
                   10631: C<timestamp> were added to the hash. C<version> will be equal to the
                   10632: total number of versions of the data that have been stored. The
                   10633: C<timestamp> attribute will be the UNIX time the hash was
                   10634: stored. C<keys> is available in every historical section to list which
                   10635: keys were added or changed at a specific historical revision of a
                   10636: hash.
                   10637: 
                   10638: B<Warning>: do not store the hash that restore returns directly. This
                   10639: will cause a mess since it will restore the historical keys as if the
                   10640: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10641: 
1.394     bowersj2 10642: Calling convention:
1.191     harris41 10643: 
1.394     bowersj2 10644:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10645:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10646: 
1.394     bowersj2 10647: For more detailed information, see lonnet specific documentation.
1.191     harris41 10648: 
1.394     bowersj2 10649: =head1 RETURN MESSAGES
1.191     harris41 10650: 
1.394     bowersj2 10651: =over 4
1.191     harris41 10652: 
1.394     bowersj2 10653: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10654: 
1.394     bowersj2 10655: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10656: when the connection is brought back up
1.191     harris41 10657: 
1.394     bowersj2 10658: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10659: for later delivery
1.191     harris41 10660: 
1.967     bisitz   10661: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10662: 
1.394     bowersj2 10663: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10664: that was requested
1.191     harris41 10665: 
1.243     albertel 10666: =back
1.191     harris41 10667: 
1.243     albertel 10668: =head1 PUBLIC SUBROUTINES
1.191     harris41 10669: 
1.243     albertel 10670: =head2 Session Environment Functions
1.191     harris41 10671: 
1.243     albertel 10672: =over 4
1.191     harris41 10673: 
1.394     bowersj2 10674: =item * 
                   10675: X<appenv()>
1.949     raeburn  10676: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10677: the user envirnoment file, and will be restored for each access this
1.620     albertel 10678: user makes during this session, also modifies the %env for the current
1.949     raeburn  10679: process. Optional rolesarrayref - if defined contains a reference to an array
                   10680: of roles which are exempt from the restriction on modifying user.role entries 
                   10681: in the user's environment.db and in %env.    
1.191     harris41 10682: 
                   10683: =item *
1.394     bowersj2 10684: X<delenv()>
1.987     raeburn  10685: B<delenv($delthis,$regexp)>: removes all items from the session
                   10686: environment file that begin with $delthis. If the 
                   10687: optional second arg - $regexp - is true, $delthis is treated as a 
                   10688: regular expression, otherwise \Q$delthis\E is used. 
                   10689: The values are also deleted from the current processes %env.
1.191     harris41 10690: 
1.795     albertel 10691: =item * get_env_multiple($name) 
                   10692: 
                   10693: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10694: values may be defined and end up as an array ref.
                   10695: 
                   10696: returns an array of values
                   10697: 
1.243     albertel 10698: =back
                   10699: 
                   10700: =head2 User Information
1.191     harris41 10701: 
1.243     albertel 10702: =over 4
1.191     harris41 10703: 
                   10704: =item *
1.394     bowersj2 10705: X<queryauthenticate()>
                   10706: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10707: authentication scheme
                   10708: 
                   10709: =item *
1.394     bowersj2 10710: X<authenticate()>
1.1073    raeburn  10711: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10712: authenticate user from domain's lib servers (first use the current
                   10713: one). C<$upass> should be the users password.
1.1073    raeburn  10714: $checkdefauth is optional (value is 1 if a check should be made to
                   10715:    authenticate user using default authentication method, and allow
                   10716:    account creation if username does not have account in the domain).
                   10717: $clientcancheckhost is optional (value is 1 if checking whether the
                   10718:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10719: 
                   10720: =item *
1.394     bowersj2 10721: X<homeserver()>
                   10722: B<homeserver($uname,$udom)>: find the server which has
                   10723: the user's directory and files (there must be only one), this caches
                   10724: the answer, and also caches if there is a borken connection.
1.191     harris41 10725: 
                   10726: =item *
1.394     bowersj2 10727: X<idget()>
                   10728: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10729: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10730: username, and only 1 username per ID in a specific domain) (returns
                   10731: hash: id=>name,id=>name)
1.191     harris41 10732: 
                   10733: =item *
1.394     bowersj2 10734: X<idrget()>
                   10735: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10736: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10737: 
                   10738: =item *
1.394     bowersj2 10739: X<idput()>
                   10740: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10741: 
                   10742: =item *
1.394     bowersj2 10743: X<rolesinit()>
                   10744: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10745: 
                   10746: =item *
1.551     albertel 10747: X<getsection()>
                   10748: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10749: course $cname, return section name/number or '' for "not in course"
                   10750: and '-1' for "no section"
                   10751: 
                   10752: =item *
1.394     bowersj2 10753: X<userenvironment()>
                   10754: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10755: passed in @what from the requested user's environment, returns a hash
                   10756: 
1.858     raeburn  10757: =item * 
                   10758: X<userlog_query()>
1.859     albertel 10759: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10760: activity.log file. %filters defines filters applied when parsing the
                   10761: log file. These can be start or end timestamps, or the type of action
                   10762: - log to look for Login or Logout events, check for Checkin or
                   10763: Checkout, role for role selection. The response is in the form
                   10764: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10765: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10766: 
1.243     albertel 10767: =back
                   10768: 
                   10769: =head2 User Roles
                   10770: 
                   10771: =over 4
                   10772: 
                   10773: =item *
                   10774: 
1.810     raeburn  10775: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10776:  F: full access
                   10777:  U,I,K: authentication modes (cxx only)
                   10778:  '': forbidden
                   10779:  1: user needs to choose course
                   10780:  2: browse allowed
1.766     albertel 10781:  A: passphrase authentication needed
1.243     albertel 10782: 
                   10783: =item *
                   10784: 
                   10785: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10786: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10787: and course level
                   10788: 
                   10789: =item *
                   10790: 
1.988     raeburn  10791: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10792: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10793: $type is Course (default) or Community.
1.988     raeburn  10794: If $forcedefault evaluates to true, text returned will be default 
                   10795: text for $type. Otherwise, if this is a course, the text returned 
                   10796: will be a custom name for the role (if defined in the course's 
                   10797: environment).  If no custom name is defined the default is returned.
                   10798:    
1.832     raeburn  10799: =item *
                   10800: 
1.935     raeburn  10801: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10802: All arguments are optional. Returns a hash of a roles, either for
                   10803: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10804: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10805: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10806: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10807: For each key, value is set to colon-separated start and end times for
                   10808: the role.  If no username and domain are specified, will default to
1.934     raeburn  10809: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10810: of role statuses (active, future or previous), roles 
                   10811: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10812: to restrict the list of roles reported. If no array ref is 
                   10813: provided for types, will default to return only active roles.
1.834     albertel 10814: 
1.243     albertel 10815: =back
                   10816: 
                   10817: =head2 User Modification
                   10818: 
                   10819: =over 4
                   10820: 
                   10821: =item *
                   10822: 
1.957     raeburn  10823: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10824: user for the level given by URL.  Optional start and end dates (leave empty
                   10825: string or zero for "no date")
1.191     harris41 10826: 
                   10827: =item *
                   10828: 
1.243     albertel 10829: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10830: change a users, password, possible return values are: ok,
                   10831: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10832: refused
1.191     harris41 10833: 
                   10834: =item *
                   10835: 
1.243     albertel 10836: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10837: 
                   10838: =item *
                   10839: 
1.1058    raeburn  10840: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10841:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10842: 
                   10843: will update user information (firstname,middlename,lastname,generation,
                   10844: permanentemail), and if forceid is true, student/employee ID also.
                   10845: A user's institutional affiliation(s) can also be updated.
                   10846: User information fields will not be overwritten with empty entries 
                   10847: unless the field is included in the $candelete array reference.
                   10848: This array is included when a single user is modified via "Manage Users",
                   10849: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10850: 
                   10851: =item *
                   10852: 
1.286     matthew  10853: modifystudent
                   10854: 
1.957     raeburn  10855: modify a student's enrollment and identification information.
1.286     matthew  10856: The course id is resolved based on the current users environment.  
                   10857: This means the envoking user must be a course coordinator or otherwise
                   10858: associated with a course.
                   10859: 
1.297     matthew  10860: This call is essentially a wrapper for lonnet::modifyuser and
                   10861: lonnet::modify_student_enrollment
1.286     matthew  10862: 
                   10863: Inputs: 
                   10864: 
                   10865: =over 4
                   10866: 
1.957     raeburn  10867: =item B<$udom> Student's loncapa domain
1.286     matthew  10868: 
1.957     raeburn  10869: =item B<$uname> Student's loncapa login name
1.286     matthew  10870: 
1.964     bisitz   10871: =item B<$uid> Student/Employee ID
1.286     matthew  10872: 
1.957     raeburn  10873: =item B<$umode> Student's authentication mode
1.286     matthew  10874: 
1.957     raeburn  10875: =item B<$upass> Student's password
1.286     matthew  10876: 
1.957     raeburn  10877: =item B<$first> Student's first name
1.286     matthew  10878: 
1.957     raeburn  10879: =item B<$middle> Student's middle name
1.286     matthew  10880: 
1.957     raeburn  10881: =item B<$last> Student's last name
1.286     matthew  10882: 
1.957     raeburn  10883: =item B<$gene> Student's generation
1.286     matthew  10884: 
1.957     raeburn  10885: =item B<$usec> Student's section in course
1.286     matthew  10886: 
                   10887: =item B<$end> Unix time of the roles expiration
                   10888: 
                   10889: =item B<$start> Unix time of the roles start date
                   10890: 
                   10891: =item B<$forceid> If defined, allow $uid to be changed
                   10892: 
                   10893: =item B<$desiredhome> server to use as home server for student
                   10894: 
1.957     raeburn  10895: =item B<$email> Student's permanent e-mail address
                   10896: 
                   10897: =item B<$type> Type of enrollment (auto or manual)
                   10898: 
1.963     raeburn  10899: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10900: 
                   10901: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10902: 
1.963     raeburn  10903: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10904: 
1.963     raeburn  10905: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10906: 
1.963     raeburn  10907: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10908: 
1.286     matthew  10909: =back
1.297     matthew  10910: 
                   10911: =item *
                   10912: 
                   10913: modify_student_enrollment
                   10914: 
                   10915: Change a students enrollment status in a class.  The environment variable
                   10916: 'role.request.course' must be defined for this function to proceed.
                   10917: 
                   10918: Inputs:
                   10919: 
                   10920: =over 4
                   10921: 
                   10922: =item $udom, students domain
                   10923: 
                   10924: =item $uname, students name
                   10925: 
                   10926: =item $uid, students user id
                   10927: 
                   10928: =item $first, students first name
                   10929: 
                   10930: =item $middle
                   10931: 
                   10932: =item $last
                   10933: 
                   10934: =item $gene
                   10935: 
                   10936: =item $usec
                   10937: 
                   10938: =item $end
                   10939: 
                   10940: =item $start
                   10941: 
1.957     raeburn  10942: =item $type
                   10943: 
                   10944: =item $locktype
                   10945: 
                   10946: =item $cid
                   10947: 
                   10948: =item $selfenroll
                   10949: 
                   10950: =item $context
                   10951: 
1.297     matthew  10952: =back
                   10953: 
1.191     harris41 10954: 
                   10955: =item *
                   10956: 
1.243     albertel 10957: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10958: custom role; give a custom role to a user for the level given by URL.  Specify
                   10959: name and domain of role author, and role name
1.191     harris41 10960: 
                   10961: =item *
                   10962: 
1.243     albertel 10963: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10964: 
                   10965: =item *
                   10966: 
1.243     albertel 10967: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10968: 
                   10969: =back
                   10970: 
                   10971: =head2 Course Infomation
                   10972: 
                   10973: =over 4
1.191     harris41 10974: 
                   10975: =item *
                   10976: 
1.631     albertel 10977: coursedescription($courseid) : returns a hash of information about the
                   10978: specified course id, including all environment settings for the
                   10979: course, the description of the course will be in the hash under the
                   10980: key 'description'
1.191     harris41 10981: 
                   10982: =item *
                   10983: 
1.624     albertel 10984: resdata($name,$domain,$type,@which) : request for current parameter
                   10985: setting for a specific $type, where $type is either 'course' or 'user',
                   10986: @what should be a list of parameters to ask about. This routine caches
                   10987: answers for 5 minutes.
1.243     albertel 10988: 
1.877     foxr     10989: =item *
                   10990: 
                   10991: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10992: data base, returning a hash that is keyed by the resource name and has
                   10993: values that are the resource value.  I believe that the timestamps and
                   10994: versions are also returned.
                   10995: 
                   10996: 
1.243     albertel 10997: =back
                   10998: 
                   10999: =head2 Course Modification
                   11000: 
                   11001: =over 4
1.191     harris41 11002: 
                   11003: =item *
                   11004: 
1.243     albertel 11005: writecoursepref($courseid,%prefs) : write preferences (environment
                   11006: database) for a course
1.191     harris41 11007: 
                   11008: =item *
                   11009: 
1.1011    raeburn  11010: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11011: 
                   11012: =item *
                   11013: 
1.1038    raeburn  11014: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11015: 
                   11016: =back
                   11017: 
                   11018: =head2 Resource Subroutines
                   11019: 
                   11020: =over 4
1.191     harris41 11021: 
                   11022: =item *
                   11023: 
1.243     albertel 11024: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11025: 
                   11026: =item *
                   11027: 
1.243     albertel 11028: repcopy($filename) : subscribes to the requested file, and attempts to
                   11029: replicate from the owning library server, Might return
1.607     raeburn  11030: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11031: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11032: resource. Expects the local filesystem pathname
                   11033: (/home/httpd/html/res/....)
                   11034: 
                   11035: =back
                   11036: 
                   11037: =head2 Resource Information
                   11038: 
                   11039: =over 4
1.191     harris41 11040: 
                   11041: =item *
                   11042: 
1.243     albertel 11043: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11044: a vairety of different possible values, $varname should be a request
                   11045: string, and the other parameters can be used to specify who and what
                   11046: one is asking about.
                   11047: 
                   11048: Possible values for $varname are environment.lastname (or other item
                   11049: from the envirnment hash), user.name (or someother aspect about the
                   11050: user), resource.0.maxtries (or some other part and parameter of a
                   11051: resource)
1.204     albertel 11052: 
                   11053: =item *
                   11054: 
1.243     albertel 11055: directcondval($number) : get current value of a condition; reads from a state
                   11056: string
1.204     albertel 11057: 
                   11058: =item *
                   11059: 
1.243     albertel 11060: condval($condidx) : value of condition index based on state
1.204     albertel 11061: 
                   11062: =item *
                   11063: 
1.243     albertel 11064: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11065: resource's metadata, $what should be either a specific key, or either
                   11066: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11067: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11068: 
                   11069: this function automatically caches all requests
1.191     harris41 11070: 
                   11071: =item *
                   11072: 
1.243     albertel 11073: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11074: network of library servers; returns file handle of where SQL and regex results
                   11075: will be stored for query
1.191     harris41 11076: 
                   11077: =item *
                   11078: 
1.243     albertel 11079: symbread($filename) : return symbolic list entry (filename argument optional);
                   11080: returns the data handle
1.191     harris41 11081: 
                   11082: =item *
                   11083: 
1.243     albertel 11084: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11085: a possible symb for the URL in $thisfn, and if is an encryypted
                   11086: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11087: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11088: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11089: 
1.191     harris41 11090: 
                   11091: =item *
                   11092: 
1.243     albertel 11093: symbclean($symb) : removes versions numbers from a symb, returns the
                   11094: cleaned symb
1.191     harris41 11095: 
                   11096: =item *
                   11097: 
1.243     albertel 11098: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11099: course map, user must be in a course for it to work.
1.191     harris41 11100: 
                   11101: =item *
                   11102: 
1.243     albertel 11103: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11104: 
                   11105: =item *
                   11106: 
1.243     albertel 11107: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11108: a random seed, all arguments are optional, if they aren't sent it uses the
                   11109: environment to derive them. Note: if symb isn't sent and it can't get one
                   11110: from &symbread it will use the current time as its return value
1.191     harris41 11111: 
                   11112: =item *
                   11113: 
1.243     albertel 11114: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11115: unfakeable, receipt
1.191     harris41 11116: 
                   11117: =item *
                   11118: 
1.620     albertel 11119: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11120: 
                   11121: =item *
                   11122: 
1.243     albertel 11123: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: 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 11128: 
                   11129: =item *
                   11130: 
1.243     albertel 11131: 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 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11140: forcing spreadsheet to reevaluate the resource scores next time.
                   11141: 
                   11142: =back
                   11143: 
                   11144: =head2 Storing/Retreiving Data
                   11145: 
                   11146: =over 4
1.191     harris41 11147: 
                   11148: =item *
                   11149: 
1.243     albertel 11150: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11151: for this url; hashref needs to be given and should be a \%hashname; the
                   11152: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11153: be derived from the env
1.191     harris41 11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11158: uses critical subroutine
1.191     harris41 11159: 
                   11160: =item *
                   11161: 
1.243     albertel 11162: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11163: all args are optional
1.191     harris41 11164: 
                   11165: =item *
                   11166: 
1.717     albertel 11167: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11168: dumps the complete (or key matching regexp) namespace into a hash
                   11169: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11170: normally &store()ed into
                   11171: 
                   11172: $range should be either an integer '100' (give me the first 100
                   11173:                                            matching records)
                   11174:               or be  two integers sperated by a - with no spaces
                   11175:                  '30-50' (give me the 30th through the 50th matching
                   11176:                           records)
                   11177: 
                   11178: 
                   11179: =item *
                   11180: 
                   11181: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11182: replaces a &store() version of data with a replacement set of data
                   11183: for a particular resource in a namespace passed in the $storehash hash 
                   11184: reference
                   11185: 
                   11186: =item *
                   11187: 
1.243     albertel 11188: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11189: works very similar to store/cstore, but all data is stored in a
                   11190: temporary location and can be reset using tmpreset, $storehash should
                   11191: be a hash reference, returns nothing on success
1.191     harris41 11192: 
                   11193: =item *
                   11194: 
1.243     albertel 11195: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11196: similar to restore, but all data is stored in a temporary location and
                   11197: can be reset using tmpreset. Returns a hash of values on success,
                   11198: error string otherwise.
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.243     albertel 11202: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11203: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11204: 
                   11205: =item *
                   11206: 
1.243     albertel 11207: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11208: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11209: 
                   11210: =item *
                   11211: 
1.243     albertel 11212: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11213: namesp ($udom and $uname are optional)
1.191     harris41 11214: 
                   11215: =item *
                   11216: 
1.702     albertel 11217: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11218: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11219: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11220: 
1.702     albertel 11221: $range should be either an integer '100' (give me the first 100
                   11222:                                            matching records)
                   11223:               or be  two integers sperated by a - with no spaces
                   11224:                  '30-50' (give me the 30th through the 50th matching
                   11225:                           records)
1.449     matthew  11226: =item *
                   11227: 
                   11228: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11229: $store can be a scalar, an array reference, or if the amount to be 
                   11230: incremented is > 1, a hash reference.
                   11231: 
                   11232: ($udom and $uname are optional)
1.191     harris41 11233: 
                   11234: =item *
                   11235: 
1.243     albertel 11236: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11237: ($udom and $uname are optional)
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: cput($namespace,$storehash,$udom,$uname) : critical put
                   11242: ($udom and $uname are optional)
1.191     harris41 11243: 
                   11244: =item *
                   11245: 
1.748     albertel 11246: newput($namespace,$storehash,$udom,$uname) :
                   11247: 
                   11248: Attempts to store the items in the $storehash, but only if they don't
                   11249: currently exist, if this succeeds you can be certain that you have 
                   11250: successfully created a new key value pair in the $namespace db.
                   11251: 
                   11252: 
                   11253: Args:
                   11254:  $namespace: name of database to store values to
                   11255:  $storehash: hashref to store to the db
                   11256:  $udom: (optional) domain of user containing the db
                   11257:  $uname: (optional) name of user caontaining the db
                   11258: 
                   11259: Returns:
                   11260:  'ok' -> succeeded in storing all keys of $storehash
                   11261:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11262:                         least <key> already existed in the db (other
                   11263:                         requested keys may also already exist)
1.967     bisitz   11264:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11265:  'con_lost' -> unable to contact request server
                   11266:  'refused' -> action was not allowed by remote machine
                   11267: 
                   11268: 
                   11269: =item *
                   11270: 
1.243     albertel 11271: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11272: reference filled in from namesp (encrypts the return communication)
                   11273: ($udom and $uname are optional)
1.191     harris41 11274: 
                   11275: =item *
                   11276: 
1.243     albertel 11277: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11278: critical subroutine
                   11279: 
1.806     raeburn  11280: =item *
                   11281: 
1.860     raeburn  11282: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11283: array reference filled in from namespace found in domain level on either
                   11284: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11285: 
                   11286: =item *
                   11287: 
1.860     raeburn  11288: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11289: domain level either on specified domain server ($uhome) or primary domain 
                   11290: server ($udom and $uhome are optional)
1.806     raeburn  11291: 
1.943     raeburn  11292: =item * 
                   11293: 
                   11294: get_domain_defaults($target_domain) : returns hash with defaults for
                   11295: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11296: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11297: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11298: Values are retrieved from cache (if current), or from domain's configuration.db
                   11299: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11300: or lonTabs/domain.tab. 
                   11301: 
                   11302: %domdefaults = &get_auth_defaults($target_domain);
                   11303: 
1.243     albertel 11304: =back
                   11305: 
                   11306: =head2 Network Status Functions
                   11307: 
                   11308: =over 4
1.191     harris41 11309: 
                   11310: =item *
                   11311: 
                   11312: dirlist($uri) : return directory list based on URI
                   11313: 
                   11314: =item *
                   11315: 
1.243     albertel 11316: spareserver() : find server with least workload from spare.tab
                   11317: 
1.986     foxr     11318: 
                   11319: =item *
                   11320: 
                   11321: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11322: if there is no corresponding loncapa host.
                   11323: 
1.243     albertel 11324: =back
                   11325: 
1.986     foxr     11326: 
1.243     albertel 11327: =head2 Apache Request
                   11328: 
                   11329: =over 4
1.191     harris41 11330: 
                   11331: =item *
                   11332: 
1.243     albertel 11333: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11334: localhost, posts hash
                   11335: 
                   11336: =back
                   11337: 
                   11338: =head2 Data to String to Data
                   11339: 
                   11340: =over 4
1.191     harris41 11341: 
                   11342: =item *
                   11343: 
1.243     albertel 11344: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11345: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11346: 
                   11347: =item *
                   11348: 
1.243     albertel 11349: hashref2str($hashref) : convert a hashref into a string complete with
                   11350: escaping and '=' and '&' separators, supports elements that are
                   11351: arrayrefs and hashrefs
1.191     harris41 11352: 
                   11353: =item *
                   11354: 
1.243     albertel 11355: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11356: with escaping and '&' separators, supports elements that are arrayrefs
                   11357: and hashrefs
1.191     harris41 11358: 
                   11359: =item *
                   11360: 
1.243     albertel 11361: str2hash($string) : convert string to hash using unescaping and
                   11362: splitting on '=' and '&', supports elements that are arrayrefs and
                   11363: hashrefs
1.191     harris41 11364: 
                   11365: =item *
                   11366: 
1.243     albertel 11367: str2array($string) : convert string to hash using unescaping and
                   11368: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11369: 
                   11370: =back
                   11371: 
                   11372: =head2 Logging Routines
                   11373: 
                   11374: =over 4
                   11375: 
                   11376: These routines allow one to make log messages in the lonnet.log and
                   11377: lonnet.perm logfiles.
1.191     harris41 11378: 
                   11379: =item *
                   11380: 
1.243     albertel 11381: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11382: 
                   11383: =item *
                   11384: 
1.243     albertel 11385: logthis() : append message to the normal lonnet.log file, it gets
                   11386: preiodically rolled over and deleted.
1.191     harris41 11387: 
                   11388: =item *
                   11389: 
1.243     albertel 11390: logperm() : append a permanent message to lonnet.perm.log, this log
                   11391: file never gets deleted by any automated portion of the system, only
                   11392: messages of critical importance should go in here.
                   11393: 
                   11394: =back
                   11395: 
                   11396: =head2 General File Helper Routines
                   11397: 
                   11398: =over 4
1.191     harris41 11399: 
                   11400: =item *
                   11401: 
1.481     raeburn  11402: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11403: (a) files in /uploaded
                   11404:   (i) If a local copy of the file exists - 
                   11405:       compares modification date of local copy with last-modified date for 
                   11406:       definitive version stored on home server for course. If local copy is 
                   11407:       stale, requests a new version from the home server and stores it. 
                   11408:       If the original has been removed from the home server, then local copy 
                   11409:       is unlinked.
                   11410:   (ii) If local copy does not exist -
                   11411:       requests the file from the home server and stores it. 
                   11412:   
                   11413:   If $caller is 'uploadrep':  
                   11414:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11415:     for request for files originally uploaded via DOCS. 
                   11416:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11417:   
                   11418:   Otherwise:
                   11419:      This indicates a call from the content generation phase of the request.
                   11420:      -  returns the entire contents of the file or -1.
                   11421:      
                   11422: (b) files in /res
                   11423:    - returns the entire contents of a file or -1; 
                   11424:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11425: 
1.712     albertel 11426: 
                   11427: =item *
                   11428: 
                   11429: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11430:                   reference
                   11431: 
                   11432: returns either a stat() list of data about the file or an empty list
                   11433: if the file doesn't exist or couldn't find out about it (connection
                   11434: problems or user unknown)
                   11435: 
1.191     harris41 11436: =item *
                   11437: 
1.243     albertel 11438: filelocation($dir,$file) : returns file system location of a file
                   11439: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11440: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11441: and a file of ../bob will become /a/bob)
1.191     harris41 11442: 
                   11443: =item *
                   11444: 
                   11445: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11446: filelocation except for hrefs
                   11447: 
                   11448: =item *
                   11449: 
                   11450: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11451: 
1.243     albertel 11452: =back
                   11453: 
1.608     albertel 11454: =head2 Usererfile file routines (/uploaded*)
                   11455: 
                   11456: =over 4
                   11457: 
                   11458: =item *
                   11459: 
                   11460: userfileupload(): main rotine for putting a file in a user or course's
                   11461:                   filespace, arguments are,
                   11462: 
1.620     albertel 11463:  formname - required - this is the name of the element in $env where the
1.608     albertel 11464:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11465:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11466:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11467:  context - if coursedoc, store the file in the course of the active role
                   11468:              of the current user; 
                   11469:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11470:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11471:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11472:          if undefined, it will be placed in "unknown"
                   11473: 
                   11474:  (This routine calls clean_filename() to remove any dangerous
                   11475:  characters from the filename, and then calls finuserfileupload() to
                   11476:  complete the transaction)
                   11477: 
                   11478:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11479:  and /adm/notfound.html if unsuccessful
                   11480: 
                   11481: =item *
                   11482: 
                   11483: clean_filename(): routine for cleaing a filename up for storage in
                   11484:                  userfile space, argument is:
                   11485: 
                   11486:  filename - proposed filename
                   11487: 
                   11488: returns: the new clean filename
                   11489: 
                   11490: =item *
                   11491: 
1.1090    raeburn  11492: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11493: userspace, probably shouldn't be called directly
                   11494: 
                   11495:   docuname: username or courseid of destination for the file
                   11496:   docudom: domain of user/course of destination for the file
                   11497:   formname: same as for userfileupload()
1.1090    raeburn  11498:   fname: filename (including subdirectories) for the file
                   11499:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11500:   allfiles: reference to hash used to store objects found by parser
                   11501:   codebase: reference to hash used for codebases of java objects found by parser
                   11502:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11503:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11504:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11505:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11506:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11507:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11508:   mimetype: reference to scalar to accommodate mime type determined
                   11509:             from File::MMagic if $parser = parse.
1.608     albertel 11510: 
                   11511:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11512:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11513:  was 'overwrite').
                   11514:  
1.608     albertel 11515: 
                   11516: =item *
                   11517: 
                   11518: renameuserfile(): renames an existing userfile to a new name
                   11519: 
                   11520:   Args:
                   11521:    docuname: username or courseid of destination for the file
                   11522:    docudom: domain of user/course of destination for the file
                   11523:    old: current file name (including any subdirs under userfiles)
                   11524:    new: desired file name (including any subdirs under userfiles)
                   11525: 
                   11526: =item *
                   11527: 
                   11528: mkdiruserfile(): creates a directory is a userfiles dir
                   11529: 
                   11530:   Args:
                   11531:    docuname: username or courseid of destination for the file
                   11532:    docudom: domain of user/course of destination for the file
                   11533:    dir: dir to create (including any subdirs under userfiles)
                   11534: 
                   11535: =item *
                   11536: 
                   11537: removeuserfile(): removes a file that exists in userfiles
                   11538: 
                   11539:   Args:
                   11540:    docuname: username or courseid of destination for the file
                   11541:    docudom: domain of user/course of destination for the file
                   11542:    fname: filname to delete (including any subdirs under userfiles)
                   11543: 
                   11544: =item *
                   11545: 
                   11546: removeuploadedurl(): convience function for removeuserfile()
                   11547: 
                   11548:   Args:
                   11549:    url:  a full /uploaded/... url to delete
                   11550: 
1.747     albertel 11551: =item * 
                   11552: 
                   11553: get_portfile_permissions():
                   11554:   Args:
                   11555:     domain: domain of user or course contain the portfolio files
                   11556:     user: name of user or num of course contain the portfolio files
                   11557:   Returns:
                   11558:     hashref of a dump of the proper file_permissions.db
                   11559:    
                   11560: 
                   11561: =item * 
                   11562: 
                   11563: get_access_controls():
                   11564: 
                   11565: Args:
                   11566:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11567:   group: (optional) the group you want the files associated with
                   11568:   file: (optional) the file you want access info on
                   11569: 
                   11570: Returns:
1.749     raeburn  11571:     a hash (keys are file names) of hashes containing
                   11572:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11573:         values are XML containing access control settings (see below) 
1.747     albertel 11574: 
                   11575: Internal notes:
                   11576: 
1.749     raeburn  11577:  access controls are stored in file_permissions.db as key=value pairs.
                   11578:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11579:         where scope -> public,guest,course,group,domains or users.
                   11580:               end -> UNIX time for end of access (0 -> no end date)
                   11581:               start -> UNIX time for start of access
                   11582: 
                   11583:     value -> XML description of access control
                   11584:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11585:             <start></start>
                   11586:             <end></end>
                   11587: 
                   11588:             <password></password>  for scope type = guest
                   11589: 
                   11590:             <domain></domain>     for scope type = course or group
                   11591:             <number></number>
                   11592:             <roles id="">
                   11593:              <role></role>
                   11594:              <access></access>
                   11595:              <section></section>
                   11596:              <group></group>
                   11597:             </roles>
                   11598: 
                   11599:             <dom></dom>         for scope type = domains
                   11600: 
                   11601:             <users>             for scope type = users
                   11602:              <user>
                   11603:               <uname></uname>
                   11604:               <udom></udom>
                   11605:              </user>
                   11606:             </users>
                   11607:            </scope> 
                   11608:               
                   11609:  Access data is also aggregated for each file in an additional key=value pair:
                   11610:  key -> path to file/file_name\0accesscontrol 
                   11611:  value -> reference to hash
                   11612:           hash contains key = value pairs
                   11613:           where key = uniqueID:scope_end_start
                   11614:                 value = UNIX time record was last updated
                   11615: 
                   11616:           Used to improve speed of look-ups of access controls for each file.  
                   11617:  
                   11618:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11619: 
                   11620: modify_access_controls():
                   11621: 
                   11622: Modifies access controls for a portfolio file
                   11623: Args
                   11624: 1. file name
                   11625: 2. reference to hash of required changes,
                   11626: 3. domain
                   11627: 4. username
                   11628:   where domain,username are the domain of the portfolio owner 
                   11629:   (either a user or a course) 
                   11630: 
                   11631: Returns:
                   11632: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11633: 2. result of deletions ('ok' or 'error', with error message).
                   11634: 3. reference to hash of any new or updated access controls.
                   11635: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11636:    key = integer (inbound ID)
                   11637:    value = uniqueID  
1.747     albertel 11638: 
1.608     albertel 11639: =back
                   11640: 
1.243     albertel 11641: =head2 HTTP Helper Routines
                   11642: 
                   11643: =over 4
                   11644: 
1.191     harris41 11645: =item *
                   11646: 
                   11647: escape() : unpack non-word characters into CGI-compatible hex codes
                   11648: 
                   11649: =item *
                   11650: 
                   11651: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11652: 
1.243     albertel 11653: =back
                   11654: 
                   11655: =head1 PRIVATE SUBROUTINES
                   11656: 
                   11657: =head2 Underlying communication routines (Shouldn't call)
                   11658: 
                   11659: =over 4
                   11660: 
                   11661: =item *
                   11662: 
                   11663: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11664: 
                   11665: =item *
                   11666: 
                   11667: reply() : uses subreply to send a message to remote machine, logs all failures
                   11668: 
                   11669: =item *
                   11670: 
                   11671: critical() : passes a critical message to another server; if cannot
                   11672: get through then place message in connection buffer directory and
                   11673: returns con_delayed, if incapable of saving message, returns
                   11674: con_failed
                   11675: 
                   11676: =item *
                   11677: 
                   11678: reconlonc() : tries to reconnect lonc client processes.
                   11679: 
                   11680: =back
                   11681: 
                   11682: =head2 Resource Access Logging
                   11683: 
                   11684: =over 4
                   11685: 
                   11686: =item *
                   11687: 
                   11688: flushcourselogs() : flush (save) buffer logs and access logs
                   11689: 
                   11690: =item *
                   11691: 
                   11692: courselog($what) : save message for course in hash
                   11693: 
                   11694: =item *
                   11695: 
                   11696: courseacclog($what) : save message for course using &courselog().  Perform
                   11697: special processing for specific resource types (problems, exams, quizzes, etc).
                   11698: 
1.191     harris41 11699: =item *
                   11700: 
                   11701: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11702: as a PerlChildExitHandler
1.243     albertel 11703: 
                   11704: =back
                   11705: 
                   11706: =head2 Other
                   11707: 
                   11708: =over 4
                   11709: 
                   11710: =item *
                   11711: 
                   11712: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11713: 
                   11714: =back
                   11715: 
                   11716: =cut
1.877     foxr     11717: 

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