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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1090  ! raeburn     4: # $Id: lonnet.pm,v 1.1089 2010/10/01 16:37:35 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.987     raeburn   615:     my ($delthis,$regexp) = @_;
1.56      www       616:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  617:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       618:                 "Attempt to delete from environment ".$delthis);
                    619:         return 'error';
                    620:     }
1.917     albertel  621:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    622:     if ($opened
1.915     albertel  623: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  624: 	&&
                    625: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    626: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  627: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   628: 	    if ($regexp) {
                    629:                 if ($key=~/^$delthis/) {
                    630:                     delete($env{$key});
                    631:                     delete($disk_env{$key});
                    632:                 } 
                    633:             } else {
                    634:                 if ($key=~/^\Q$delthis\E/) {
                    635: 		    delete($env{$key});
                    636: 		    delete($disk_env{$key});
                    637: 	        }
                    638:             }
1.448     albertel  639: 	}
1.783     albertel  640: 	untie(%disk_env);
1.5       www       641:     }
                    642:     return 'ok';
1.369     albertel  643: }
                    644: 
1.790     albertel  645: sub get_env_multiple {
                    646:     my ($name) = @_;
                    647:     my @values;
                    648:     if (defined($env{$name})) {
                    649:         # exists is it an array
                    650:         if (ref($env{$name})) {
                    651:             @values=@{ $env{$name} };
                    652:         } else {
                    653:             $values[0]=$env{$name};
                    654:         }
                    655:     }
                    656:     return(@values);
                    657: }
                    658: 
1.958     www       659: # ------------------------------------------------------------------- Locking
                    660: 
                    661: sub set_lock {
                    662:     my ($text)=@_;
                    663:     $locknum++;
                    664:     my $id=$$.'-'.$locknum;
                    665:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    666:              'session.lock.'.$id => $text});
                    667:     return $id;
                    668: }
                    669: 
                    670: sub get_locks {
                    671:     my $num=0;
                    672:     my %texts=();
                    673:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    674:        if ($lock=~/\w/) {
                    675:           $num++;
                    676:           $texts{$lock}=$env{'session.lock.'.$lock};
                    677:        }
                    678:    }
                    679:    return ($num,%texts);
                    680: }
                    681: 
                    682: sub remove_lock {
                    683:     my ($id)=@_;
                    684:     my $newlocks='';
                    685:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    686:        if (($lock=~/\w/) && ($lock ne $id)) {
                    687:           $newlocks.=','.$lock;
                    688:        }
                    689:     }
                    690:     &appenv({'session.locks' => $newlocks});
                    691:     &delenv('session.lock.'.$id);
                    692: }
                    693: 
                    694: sub remove_all_locks {
                    695:     my $activelocks=$env{'session.locks'};
                    696:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    697:        if ($lock=~/\w/) {
                    698:           &remove_lock($lock);
                    699:        }
                    700:     }
                    701: }
                    702: 
                    703: 
1.369     albertel  704: # ------------------------------------------ Find out current server userload
                    705: sub userload {
                    706:     my $numusers=0;
                    707:     {
                    708: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    709: 	my $filename;
                    710: 	my $curtime=time;
                    711: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  712: 	    next if ($filename eq '.' || $filename eq '..');
                    713: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  714: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  715: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  716: 	}
                    717: 	closedir(LONIDS);
                    718:     }
                    719:     my $userloadpercent=0;
                    720:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    721:     if ($maxuserload) {
1.371     albertel  722: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  723:     }
1.372     albertel  724:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  725:     return $userloadpercent;
1.283     www       726: }
                    727: 
1.1       albertel  728: # ------------------------------ Find server with least workload from spare.tab
1.11      www       729: 
1.1       albertel  730: sub spareserver {
1.1083    raeburn   731:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  732:     my $spare_server;
1.370     albertel  733:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  734:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    735:                                                      :  $userloadpercent;
1.1083    raeburn   736:     my ($uint_dom,$remotesessions);
                    737:     if (($udom ne '') && (&domain($udom) ne '')) {
                    738:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    739:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    740:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    741:         $remotesessions = $udomdefaults{'remotesessions'};
                    742:     }
1.784     albertel  743:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   744:         if ($uint_dom) {
                    745:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    746:                                           $try_server));
                    747:         }
1.784     albertel  748: 	($spare_server, $lowest_load) =
                    749: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    750:     }
                    751: 
                    752:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    753: 
                    754:     if (!$found_server) {
                    755: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   756:             if ($uint_dom) {
                    757:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    758:                                              $try_server));
                    759:             }
1.784     albertel  760: 	    ($spare_server, $lowest_load) =
                    761: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    762: 	}
                    763:     }
                    764: 
                    765:     if (!$want_server_name) {
1.968     raeburn   766:         my $protocol = 'http';
                    767:         if ($protocol{$spare_server} eq 'https') {
                    768:             $protocol = $protocol{$spare_server};
                    769:         }
1.1001    raeburn   770:         if (defined($spare_server)) {
                    771:             my $hostname = &hostname($spare_server);
1.1083    raeburn   772:             if (defined($hostname)) {
1.1001    raeburn   773: 	        $spare_server = $protocol.'://'.$hostname;
                    774:             }
                    775:         }
1.784     albertel  776:     }
                    777:     return $spare_server;
                    778: }
                    779: 
                    780: sub compare_server_load {
                    781:     my ($try_server, $spare_server, $lowest_load) = @_;
                    782: 
                    783:     my $loadans     = &reply('load',    $try_server);
                    784:     my $userloadans = &reply('userload',$try_server);
                    785: 
                    786:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072    www       787: 	return; #didn't get a number from the server
1.784     albertel  788:     }
                    789: 
                    790:     my $load;
                    791:     if ($loadans =~ /\d/) {
                    792: 	if ($userloadans =~ /\d/) {
                    793: 	    #both are numbers, pick the bigger one
                    794: 	    $load = ($loadans > $userloadans) ? $loadans 
                    795: 		                              : $userloadans;
1.411     albertel  796: 	} else {
1.784     albertel  797: 	    $load = $loadans;
1.411     albertel  798: 	}
1.784     albertel  799:     } else {
                    800: 	$load = $userloadans;
                    801:     }
                    802: 
                    803:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    804: 	$spare_server = $try_server;
                    805: 	$lowest_load  = $load;
1.370     albertel  806:     }
1.784     albertel  807:     return ($spare_server,$lowest_load);
1.202     matthew   808: }
1.914     albertel  809: 
                    810: # --------------------------- ask offload servers if user already has a session
                    811: sub find_existing_session {
                    812:     my ($udom,$uname) = @_;
                    813:     foreach my $try_server (@{ $spareid{'primary'} },
                    814: 			    @{ $spareid{'default'} }) {
                    815: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    816:     }
                    817:     return;
                    818: }
                    819: 
                    820: # -------------------------------- ask if server already has a session for user
                    821: sub has_user_session {
                    822:     my ($lonid,$udom,$uname) = @_;
                    823:     my $result = &reply(join(':','userhassession',
                    824: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    825:     return 1 if ($result eq 'ok');
                    826: 
                    827:     return 0;
                    828: }
                    829: 
1.1076    raeburn   830: # --------- determine least loaded server in a user's domain which allows login
                    831: 
                    832: sub choose_server {
                    833:     my ($udom) = @_;
                    834:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   835:     my %servers = &get_servers($udom);
1.1076    raeburn   836:     my $lowest_load = 30000;
                    837:     my ($login_host,$hostname);
                    838:     foreach my $lonhost (keys(%servers)) {
                    839:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    840:         if ($loginvia eq '') {
                    841:             ($login_host, $lowest_load) =
                    842:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    843:         }
                    844:     }
                    845:     if ($login_host ne '') {
                    846:         $hostname = $servers{$login_host};
                    847:     }
                    848:     return ($login_host,$hostname);
                    849: }
                    850: 
1.202     matthew   851: # --------------------------------------------- Try to change a user's password
                    852: 
                    853: sub changepass {
1.799     raeburn   854:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   855:     $currentpass = &escape($currentpass);
                    856:     $newpass     = &escape($newpass);
1.1030    raeburn   857:     my $lonhost = $perlvar{'lonHostID'};
                    858:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   859: 		       $server);
                    860:     if (! $answer) {
                    861: 	&logthis("No reply on password change request to $server ".
                    862: 		 "by $uname in domain $udom.");
                    863:     } elsif ($answer =~ "^ok") {
                    864:         &logthis("$uname in $udom successfully changed their password ".
                    865: 		 "on $server.");
                    866:     } elsif ($answer =~ "^pwchange_failure") {
                    867: 	&logthis("$uname in $udom was unable to change their password ".
                    868: 		 "on $server.  The action was blocked by either lcpasswd ".
                    869: 		 "or pwchange");
                    870:     } elsif ($answer =~ "^non_authorized") {
                    871:         &logthis("$uname in $udom did not get their password correct when ".
                    872: 		 "attempting to change it on $server.");
                    873:     } elsif ($answer =~ "^auth_mode_error") {
                    874:         &logthis("$uname in $udom attempted to change their password despite ".
                    875: 		 "not being locally or internally authenticated on $server.");
                    876:     } elsif ($answer =~ "^unknown_user") {
                    877:         &logthis("$uname in $udom attempted to change their password ".
                    878: 		 "on $server but were unable to because $server is not ".
                    879: 		 "their home server.");
                    880:     } elsif ($answer =~ "^refused") {
                    881: 	&logthis("$server refused to change $uname in $udom password because ".
                    882: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   883:     } elsif ($answer =~ "invalid_client") {
                    884:         &logthis("$server refused to change $uname in $udom password because ".
                    885:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   886:     }
                    887:     return $answer;
1.1       albertel  888: }
                    889: 
1.169     harris41  890: # ----------------------- Try to determine user's current authentication scheme
                    891: 
                    892: sub queryauthenticate {
                    893:     my ($uname,$udom)=@_;
1.456     albertel  894:     my $uhome=&homeserver($uname,$udom);
                    895:     if (!$uhome) {
                    896: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    897: 	return 'no_host';
                    898:     }
                    899:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    900:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    901: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  902:     }
1.456     albertel  903:     return $answer;
1.169     harris41  904: }
                    905: 
1.1       albertel  906: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       907: 
1.1       albertel  908: sub authenticate {
1.1073    raeburn   909:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  910:     $upass=&escape($upass);
                    911:     $uname= &LONCAPA::clean_username($uname);
1.836     www       912:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   913:     my $newhome;
1.836     www       914:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    915: # Maybe the machine was offline and only re-appeared again recently?
                    916:         &reconlonc();
                    917: # One more
1.952     raeburn   918: 	$uhome=&homeserver($uname,$udom,1);
                    919:         if (($uhome eq 'no_host') && $checkdefauth) {
                    920:             if (defined(&domain($udom,'primary'))) {
                    921:                 $newhome=&domain($udom,'primary');
                    922:             }
                    923:             if ($newhome ne '') {
                    924:                 $uhome = $newhome;
                    925:             }
                    926:         }
1.836     www       927: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    928: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   929: 	    return 'no_host';
                    930:         }
1.1       albertel  931:     }
1.1073    raeburn   932:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  933:     if ($answer eq 'authorized') {
1.952     raeburn   934:         if ($newhome) {
                    935:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    936:             return 'no_account_on_host'; 
                    937:         } else {
                    938:             &logthis("User $uname at $udom authorized by $uhome");
                    939:             return $uhome;
                    940:         }
1.471     albertel  941:     }
                    942:     if ($answer eq 'non_authorized') {
                    943: 	&logthis("User $uname at $udom rejected by $uhome");
                    944: 	return 'no_host'; 
1.9       www       945:     }
1.471     albertel  946:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  947:     return 'no_host';
                    948: }
                    949: 
1.1073    raeburn   950: sub can_host_session {
1.1074    raeburn   951:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn   952:     my $canhost = 1;
1.1074    raeburn   953:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn   954:     if (ref($remotesessions) eq 'HASH') {
                    955:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn   956:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn   957:                 $canhost = 0;
                    958:             } else {
                    959:                 $canhost = 1;
                    960:             }
                    961:         }
                    962:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn   963:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn   964:                 $canhost = 1;
                    965:             } else {
                    966:                 $canhost = 0;
                    967:             }
                    968:         }
                    969:         if ($canhost) {
                    970:             if ($remotesessions->{'version'} ne '') {
                    971:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    972:                 if ($reqmajor ne '' && $reqminor ne '') {
                    973:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    974:                         my $major = $1;
                    975:                         my $minor = $2;
                    976:                         if (($major < $reqmajor ) ||
                    977:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    978:                             $canhost = 0;
                    979:                         }
                    980:                     } else {
                    981:                         $canhost = 0;
                    982:                     }
                    983:                 }
                    984:             }
                    985:         }
                    986:     }
                    987:     if ($canhost) {
                    988:         if (ref($hostedsessions) eq 'HASH') {
                    989:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    990:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                    991:                     $canhost = 0;
                    992:                 } else {
                    993:                     $canhost = 1;
                    994:                 }
                    995:             }
                    996:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                    997:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                    998:                     $canhost = 1;
                    999:                 } else {
                   1000:                     $canhost = 0;
                   1001:                 }
                   1002:             }
                   1003:         }
                   1004:     }
                   1005:     return $canhost;
                   1006: }
                   1007: 
1.1083    raeburn  1008: sub spare_can_host {
                   1009:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1010:     my $canhost=1;
                   1011:     my @intdoms;
                   1012:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1013:     if (ref($internet_names) eq 'ARRAY') {
                   1014:         @intdoms = @{$internet_names};
                   1015:     }
                   1016:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1017:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1018:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1019:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1020:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1021:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1022:                                      $remotesessions,
                   1023:                                      $defdomdefaults{'hostedsessions'});
                   1024:     }
                   1025:     return $canhost;
                   1026: }
                   1027: 
1.1       albertel 1028: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1029: 
1.599     albertel 1030: my %homecache;
1.1       albertel 1031: sub homeserver {
1.230     stredwic 1032:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1033:     my $index="$uname:$udom";
1.426     albertel 1034: 
1.599     albertel 1035:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1036: 
                   1037:     my %servers = &get_servers($udom,'library');
                   1038:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1039:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1040: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1041: 
                   1042: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1043: 	if ($answer eq 'found') {
                   1044: 	    delete($badServerCache{$tryserver}); 
                   1045: 	    return $homecache{$index}=$tryserver;
                   1046: 	} elsif ($answer eq 'no_host') {
                   1047: 	    $badServerCache{$tryserver}=1;
                   1048: 	}
1.1       albertel 1049:     }    
                   1050:     return 'no_host';
1.70      www      1051: }
                   1052: 
                   1053: # ------------------------------------- Find the usernames behind a list of IDs
                   1054: 
                   1055: sub idget {
                   1056:     my ($udom,@ids)=@_;
                   1057:     my %returnhash=();
                   1058:     
1.841     albertel 1059:     my %servers = &get_servers($udom,'library');
                   1060:     foreach my $tryserver (keys(%servers)) {
                   1061: 	my $idlist=join('&',@ids);
                   1062: 	$idlist=~tr/A-Z/a-z/; 
                   1063: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1064: 	my @answer=();
                   1065: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1066: 	    @answer=split(/\&/,$reply);
                   1067: 	}                    ;
                   1068: 	my $i;
                   1069: 	for ($i=0;$i<=$#ids;$i++) {
                   1070: 	    if ($answer[$i]) {
                   1071: 		$returnhash{$ids[$i]}=$answer[$i];
                   1072: 	    } 
                   1073: 	}
                   1074:     } 
1.70      www      1075:     return %returnhash;
                   1076: }
                   1077: 
                   1078: # ------------------------------------- Find the IDs behind a list of usernames
                   1079: 
                   1080: sub idrget {
                   1081:     my ($udom,@unames)=@_;
                   1082:     my %returnhash=();
1.800     albertel 1083:     foreach my $uname (@unames) {
                   1084:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1085:     }
1.70      www      1086:     return %returnhash;
                   1087: }
                   1088: 
                   1089: # ------------------------------- Store away a list of names and associated IDs
                   1090: 
                   1091: sub idput {
                   1092:     my ($udom,%ids)=@_;
                   1093:     my %servers=();
1.800     albertel 1094:     foreach my $uname (keys(%ids)) {
                   1095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1096:         my $uhom=&homeserver($uname,$udom);
1.70      www      1097:         if ($uhom ne 'no_host') {
1.800     albertel 1098:             my $id=&escape($ids{$uname});
1.70      www      1099:             $id=~tr/A-Z/a-z/;
1.800     albertel 1100:             my $esc_unam=&escape($uname);
1.70      www      1101: 	    if ($servers{$uhom}) {
1.800     albertel 1102: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1103:             } else {
1.800     albertel 1104:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1105:             }
                   1106:         }
1.191     harris41 1107:     }
1.800     albertel 1108:     foreach my $server (keys(%servers)) {
                   1109:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1110:     }
1.344     www      1111: }
                   1112: 
1.1023    raeburn  1113: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1114: sub dump_dom {
1.1023    raeburn  1115:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1116:     if (!$udom) {
                   1117:         $udom=$env{'user.domain'};
                   1118:     }
                   1119:     my %returnhash;
1.1023    raeburn  1120:     if ($udom) {
                   1121:         my $uname = &get_domainconfiguser($udom);
                   1122:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1123:     }
                   1124:     return %returnhash;
                   1125: }
                   1126: 
1.1023    raeburn  1127: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1128: 
                   1129: sub get_dom {
1.860     raeburn  1130:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1131:     my $items='';
                   1132:     foreach my $item (@$storearr) {
                   1133:         $items.=&escape($item).'&';
                   1134:     }
                   1135:     $items=~s/\&$//;
1.860     raeburn  1136:     if (!$udom) {
                   1137:         $udom=$env{'user.domain'};
                   1138:         if (defined(&domain($udom,'primary'))) {
                   1139:             $uhome=&domain($udom,'primary');
                   1140:         } else {
1.874     albertel 1141:             undef($uhome);
1.860     raeburn  1142:         }
                   1143:     } else {
                   1144:         if (!$uhome) {
                   1145:             if (defined(&domain($udom,'primary'))) {
                   1146:                 $uhome=&domain($udom,'primary');
                   1147:             }
                   1148:         }
                   1149:     }
                   1150:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1151:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1152:         my %returnhash;
1.875     albertel 1153:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1154:             return %returnhash;
                   1155:         }
1.806     raeburn  1156:         my @pairs=split(/\&/,$rep);
                   1157:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1158:             return @pairs;
                   1159:         }
                   1160:         my $i=0;
                   1161:         foreach my $item (@$storearr) {
                   1162:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1163:             $i++;
                   1164:         }
                   1165:         return %returnhash;
                   1166:     } else {
1.880     banghart 1167:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1168:     }
                   1169: }
                   1170: 
                   1171: # -------------------------------------------- put items in domain db files 
                   1172: 
                   1173: sub put_dom {
1.860     raeburn  1174:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1175:     if (!$udom) {
                   1176:         $udom=$env{'user.domain'};
                   1177:         if (defined(&domain($udom,'primary'))) {
                   1178:             $uhome=&domain($udom,'primary');
                   1179:         } else {
1.874     albertel 1180:             undef($uhome);
1.860     raeburn  1181:         }
                   1182:     } else {
                   1183:         if (!$uhome) {
                   1184:             if (defined(&domain($udom,'primary'))) {
                   1185:                 $uhome=&domain($udom,'primary');
                   1186:             }
                   1187:         }
                   1188:     } 
                   1189:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1190:         my $items='';
                   1191:         foreach my $item (keys(%$storehash)) {
                   1192:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1193:         }
                   1194:         $items=~s/\&$//;
                   1195:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1196:     } else {
1.860     raeburn  1197:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1198:     }
                   1199: }
                   1200: 
1.1023    raeburn  1201: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1202: sub newput_dom {
1.1023    raeburn  1203:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1204:     my $result;
                   1205:     if (!$udom) {
                   1206:         $udom=$env{'user.domain'};
                   1207:     }
1.1023    raeburn  1208:     if ($udom) {
                   1209:         my $uname = &get_domainconfiguser($udom);
                   1210:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1211:     }
                   1212:     return $result;
                   1213: }
                   1214: 
1.1023    raeburn  1215: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1216: sub del_dom {
1.1023    raeburn  1217:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1218:     if (ref($storearr) eq 'ARRAY') {
                   1219:         if (!$udom) {
                   1220:             $udom=$env{'user.domain'};
                   1221:         }
1.1023    raeburn  1222:         if ($udom) {
                   1223:             my $uname = &get_domainconfiguser($udom); 
                   1224:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1225:         }
                   1226:     }
                   1227: }
                   1228: 
1.1023    raeburn  1229: # ----------------------------------construct domainconfig user for a domain 
                   1230: sub get_domainconfiguser {
                   1231:     my ($udom) = @_;
                   1232:     return $udom.'-domainconfig';
                   1233: }
                   1234: 
1.837     raeburn  1235: sub retrieve_inst_usertypes {
                   1236:     my ($udom) = @_;
                   1237:     my (%returnhash,@order);
1.989     raeburn  1238:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1239:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1240:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1241:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1242:         @order = @{$domdefs{'inststatusorder'}};
                   1243:     } else {
                   1244:         if (defined(&domain($udom,'primary'))) {
                   1245:             my $uhome=&domain($udom,'primary');
                   1246:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1247:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1248:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1249:                 return (\%returnhash,\@order);
                   1250:             }
                   1251:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1252:             my @pairs=split(/\&/,$hashitems);
                   1253:             foreach my $item (@pairs) {
                   1254:                 my ($key,$value)=split(/=/,$item,2);
                   1255:                 $key = &unescape($key);
                   1256:                 next if ($key =~ /^error: 2 /);
                   1257:                 $returnhash{$key}=&thaw_unescape($value);
                   1258:             }
                   1259:             my @esc_order = split(/\&/,$orderitems);
                   1260:             foreach my $item (@esc_order) {
                   1261:                 push(@order,&unescape($item));
                   1262:             }
                   1263:         } else {
                   1264:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1265:         }
                   1266:     }
                   1267:     return (\%returnhash,\@order);
                   1268: }
                   1269: 
1.868     raeburn  1270: sub is_domainimage {
                   1271:     my ($url) = @_;
                   1272:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1273:         if (&domain($1) ne '') {
                   1274:             return '1';
                   1275:         }
                   1276:     }
                   1277:     return;
                   1278: }
                   1279: 
1.899     raeburn  1280: sub inst_directory_query {
                   1281:     my ($srch) = @_;
                   1282:     my $udom = $srch->{'srchdomain'};
                   1283:     my %results;
                   1284:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1285:     my $outcome;
1.899     raeburn  1286:     if ($homeserver ne '') {
1.904     albertel 1287: 	my $queryid=&reply("querysend:instdirsearch:".
                   1288: 			   &escape($srch->{'srchby'}).':'.
                   1289: 			   &escape($srch->{'srchterm'}).':'.
                   1290: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1291: 	my $host=&hostname($homeserver);
                   1292: 	if ($queryid !~/^\Q$host\E\_/) {
                   1293: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1294: 	    return;
                   1295: 	}
                   1296: 	my $response = &get_query_reply($queryid);
                   1297: 	my $maxtries = 5;
                   1298: 	my $tries = 1;
                   1299: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1300: 	    $response = &get_query_reply($queryid);
                   1301: 	    $tries ++;
                   1302: 	}
                   1303: 
                   1304:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1305:             if ($response eq 'unavailable') {
                   1306:                 $outcome = $response;
                   1307:             } else {
                   1308:                 $outcome = 'ok';
                   1309:                 my @matches = split(/\n/,$response);
                   1310:                 foreach my $match (@matches) {
                   1311:                     my ($key,$value) = split(/=/,$match);
                   1312:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1313:                 }
1.899     raeburn  1314:             }
                   1315:         }
                   1316:     }
1.909     raeburn  1317:     return ($outcome,%results);
1.899     raeburn  1318: }
                   1319: 
                   1320: sub usersearch {
                   1321:     my ($srch) = @_;
                   1322:     my $dom = $srch->{'srchdomain'};
                   1323:     my %results;
                   1324:     my %libserv = &all_library();
                   1325:     my $query = 'usersearch';
                   1326:     foreach my $tryserver (keys(%libserv)) {
                   1327:         if (&host_domain($tryserver) eq $dom) {
                   1328:             my $host=&hostname($tryserver);
                   1329:             my $queryid=
1.911     raeburn  1330:                 &reply("querysend:".&escape($query).':'.
                   1331:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1332:                        &escape($srch->{'srchtype'}).':'.
                   1333:                        &escape($srch->{'srchterm'}),$tryserver);
                   1334:             if ($queryid !~/^\Q$host\E\_/) {
                   1335:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1336:                 next;
1.899     raeburn  1337:             }
                   1338:             my $reply = &get_query_reply($queryid);
                   1339:             my $maxtries = 1;
                   1340:             my $tries = 1;
                   1341:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1342:                 $reply = &get_query_reply($queryid);
                   1343:                 $tries ++;
                   1344:             }
                   1345:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1346:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1347:             } else {
1.911     raeburn  1348:                 my @matches;
                   1349:                 if ($reply =~ /\n/) {
                   1350:                     @matches = split(/\n/,$reply);
                   1351:                 } else {
                   1352:                     @matches = split(/\&/,$reply);
                   1353:                 }
1.899     raeburn  1354:                 foreach my $match (@matches) {
                   1355:                     my ($uname,$udom,%userhash);
1.911     raeburn  1356:                     foreach my $entry (split(/:/,$match)) {
                   1357:                         my ($key,$value) =
                   1358:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1359:                         $userhash{$key} = $value;
                   1360:                         if ($key eq 'username') {
                   1361:                             $uname = $value;
                   1362:                         } elsif ($key eq 'domain') {
                   1363:                             $udom = $value;
1.911     raeburn  1364:                         }
1.899     raeburn  1365:                     }
                   1366:                     $results{$uname.':'.$udom} = \%userhash;
                   1367:                 }
                   1368:             }
                   1369:         }
                   1370:     }
                   1371:     return %results;
                   1372: }
                   1373: 
1.912     raeburn  1374: sub get_instuser {
                   1375:     my ($udom,$uname,$id) = @_;
                   1376:     my $homeserver = &domain($udom,'primary');
                   1377:     my ($outcome,%results);
                   1378:     if ($homeserver ne '') {
                   1379:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1380:                            &escape($id).':'.&escape($udom),$homeserver);
                   1381:         my $host=&hostname($homeserver);
                   1382:         if ($queryid !~/^\Q$host\E\_/) {
                   1383:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1384:             return;
                   1385:         }
                   1386:         my $response = &get_query_reply($queryid);
                   1387:         my $maxtries = 5;
                   1388:         my $tries = 1;
                   1389:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1390:             $response = &get_query_reply($queryid);
                   1391:             $tries ++;
                   1392:         }
                   1393:         if (!&error($response) && $response ne 'refused') {
                   1394:             if ($response eq 'unavailable') {
                   1395:                 $outcome = $response;
                   1396:             } else {
                   1397:                 $outcome = 'ok';
                   1398:                 my @matches = split(/\n/,$response);
                   1399:                 foreach my $match (@matches) {
                   1400:                     my ($key,$value) = split(/=/,$match);
                   1401:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1402:                 }
                   1403:             }
                   1404:         }
                   1405:     }
                   1406:     my %userinfo;
                   1407:     if (ref($results{$uname}) eq 'HASH') {
                   1408:         %userinfo = %{$results{$uname}};
                   1409:     } 
                   1410:     return ($outcome,%userinfo);
                   1411: }
                   1412: 
                   1413: sub inst_rulecheck {
1.923     raeburn  1414:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1415:     my %returnhash;
                   1416:     if ($udom ne '') {
                   1417:         if (ref($rules) eq 'ARRAY') {
                   1418:             @{$rules} = map {&escape($_);} (@{$rules});
                   1419:             my $rulestr = join(':',@{$rules});
                   1420:             my $homeserver=&domain($udom,'primary');
                   1421:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1422:                 my $response;
                   1423:                 if ($item eq 'username') {                
                   1424:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1425:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1426:                                               $homeserver));
1.923     raeburn  1427:                 } elsif ($item eq 'id') {
                   1428:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1429:                                               ':'.&escape($id).':'.$rulestr,
                   1430:                                               $homeserver));
1.945     raeburn  1431:                 } elsif ($item eq 'selfcreate') {
                   1432:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1433:                                                &escape($udom).':'.&escape($uname).
                   1434:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1435:                 }
1.912     raeburn  1436:                 if ($response ne 'refused') {
                   1437:                     my @pairs=split(/\&/,$response);
                   1438:                     foreach my $item (@pairs) {
                   1439:                         my ($key,$value)=split(/=/,$item,2);
                   1440:                         $key = &unescape($key);
                   1441:                         next if ($key =~ /^error: 2 /);
                   1442:                         $returnhash{$key}=&thaw_unescape($value);
                   1443:                     }
                   1444:                 }
                   1445:             }
                   1446:         }
                   1447:     }
                   1448:     return %returnhash;
                   1449: }
                   1450: 
                   1451: sub inst_userrules {
1.923     raeburn  1452:     my ($udom,$check) = @_;
1.912     raeburn  1453:     my (%ruleshash,@ruleorder);
                   1454:     if ($udom ne '') {
                   1455:         my $homeserver=&domain($udom,'primary');
                   1456:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1457:             my $response;
                   1458:             if ($check eq 'id') {
                   1459:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1460:                                  $homeserver);
1.943     raeburn  1461:             } elsif ($check eq 'email') {
                   1462:                 $response=&reply('instemailrules:'.&escape($udom),
                   1463:                                  $homeserver);
1.923     raeburn  1464:             } else {
                   1465:                 $response=&reply('instuserrules:'.&escape($udom),
                   1466:                                  $homeserver);
                   1467:             }
1.912     raeburn  1468:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1469:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1470:                 ($response ne 'no_such_host')) {
                   1471:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1472:                 my @pairs=split(/\&/,$hashitems);
                   1473:                 foreach my $item (@pairs) {
                   1474:                     my ($key,$value)=split(/=/,$item,2);
                   1475:                     $key = &unescape($key);
                   1476:                     next if ($key =~ /^error: 2 /);
                   1477:                     $ruleshash{$key}=&thaw_unescape($value);
                   1478:                 }
                   1479:                 my @esc_order = split(/\&/,$orderitems);
                   1480:                 foreach my $item (@esc_order) {
                   1481:                     push(@ruleorder,&unescape($item));
                   1482:                 }
                   1483:             }
                   1484:         }
                   1485:     }
                   1486:     return (\%ruleshash,\@ruleorder);
                   1487: }
                   1488: 
1.976     raeburn  1489: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1490: 
                   1491: sub get_domain_defaults {
                   1492:     my ($domain) = @_;
                   1493:     my $cachetime = 60*60*24;
                   1494:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1495:     if (defined($cached)) {
                   1496:         if (ref($result) eq 'HASH') {
                   1497:             return %{$result};
                   1498:         }
                   1499:     }
                   1500:     my %domdefaults;
                   1501:     my %domconfig =
1.989     raeburn  1502:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1503:                                   'requestcourses','inststatus',
1.1073    raeburn  1504:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1505:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1506:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1507:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1508:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1509:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1510:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1511:     } else {
                   1512:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1513:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1514:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1515:     }
1.976     raeburn  1516:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1517:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1518:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1519:         } else {
                   1520:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1521:         } 
                   1522:         my @usertools = ('aboutme','blog','portfolio');
                   1523:         foreach my $item (@usertools) {
                   1524:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1525:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1526:             }
                   1527:         }
                   1528:     }
1.985     raeburn  1529:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1530:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1531:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1532:         }
                   1533:     }
1.989     raeburn  1534:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1535:         foreach my $item ('inststatustypes','inststatusorder') {
                   1536:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1537:         }
                   1538:     }
1.1047    raeburn  1539:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1540:         foreach my $item ('canuse_pdfforms') {
                   1541:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1542:         }
                   1543:     }
1.1073    raeburn  1544:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1545:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1546:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1547:         }
                   1548:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1549:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1550:         }
                   1551:     }
1.943     raeburn  1552:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1553:                                   $cachetime);
                   1554:     return %domdefaults;
                   1555: }
                   1556: 
1.344     www      1557: # --------------------------------------------------- Assign a key to a student
                   1558: 
                   1559: sub assign_access_key {
1.364     www      1560: #
                   1561: # a valid key looks like uname:udom#comments
                   1562: # comments are being appended
                   1563: #
1.498     www      1564:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1565:     $kdom=
1.620     albertel 1566:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1567:     $knum=
1.620     albertel 1568:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1569:     $cdom=
1.620     albertel 1570:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1571:     $cnum=
1.620     albertel 1572:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1573:     $udom=$env{'user.name'} unless (defined($udom));
                   1574:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1575:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1576:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1577:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1578:                                                   # assigned to this person
                   1579:                                                   # - this should not happen,
1.345     www      1580:                                                   # unless something went wrong
                   1581:                                                   # the first time around
                   1582: # ready to assign
1.364     www      1583:         $logentry=$1.'; '.$logentry;
1.496     www      1584:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1585:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1586: # key now belongs to user
1.346     www      1587: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1588:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1589:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1590:                 return 'ok';
                   1591:             } else {
                   1592:                 return 
                   1593:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1594: 	    }
                   1595:         } else {
                   1596:             return 'error: Could not assign key, try again later.';
                   1597:         }
1.364     www      1598:     } elsif (!$existing{$ckey}) {
1.345     www      1599: # the key does not exist
                   1600: 	return 'error: The key does not exist';
                   1601:     } else {
                   1602: # the key is somebody else's
                   1603: 	return 'error: The key is already in use';
                   1604:     }
1.344     www      1605: }
                   1606: 
1.364     www      1607: # ------------------------------------------ put an additional comment on a key
                   1608: 
                   1609: sub comment_access_key {
                   1610: #
                   1611: # a valid key looks like uname:udom#comments
                   1612: # comments are being appended
                   1613: #
                   1614:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1615:     $cdom=
1.620     albertel 1616:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1617:     $cnum=
1.620     albertel 1618:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1619:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1620:     if ($existing{$ckey}) {
                   1621:         $existing{$ckey}.='; '.$logentry;
                   1622: # ready to assign
1.367     www      1623:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1624:                                                  $cdom,$cnum) eq 'ok') {
                   1625: 	    return 'ok';
                   1626:         } else {
                   1627: 	    return 'error: Count not store comment.';
                   1628:         }
                   1629:     } else {
                   1630: # the key does not exist
                   1631: 	return 'error: The key does not exist';
                   1632:     }
                   1633: }
                   1634: 
1.344     www      1635: # ------------------------------------------------------ Generate a set of keys
                   1636: 
                   1637: sub generate_access_keys {
1.364     www      1638:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1639:     $cdom=
1.620     albertel 1640:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1641:     $cnum=
1.620     albertel 1642:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1643:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1644:     unless (($cdom) && ($cnum)) { return 0; }
                   1645:     if ($number>10000) { return 0; }
                   1646:     sleep(2); # make sure don't get same seed twice
                   1647:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1648:     my $total=0;
                   1649:     for (my $i=1;$i<=$number;$i++) {
                   1650:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1651:                   sprintf("%lx",int(100000*rand)).'-'.
                   1652:                   sprintf("%lx",int(100000*rand));
                   1653:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1654:        $newkey=~s/0/h/g; # and also 0 and O
                   1655:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1656:        if ($existing{$newkey}) {
                   1657:            $i--;
                   1658:        } else {
1.364     www      1659: 	  if (&put('accesskeys',
                   1660:               { $newkey => '# generated '.localtime().
1.620     albertel 1661:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1662:                            '; '.$logentry },
                   1663: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1664:               $total++;
                   1665: 	  }
                   1666:        }
                   1667:     }
1.620     albertel 1668:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1669:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1670:     return $total;
                   1671: }
                   1672: 
                   1673: # ------------------------------------------------------- Validate an accesskey
                   1674: 
                   1675: sub validate_access_key {
                   1676:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1677:     $cdom=
1.620     albertel 1678:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1679:     $cnum=
1.620     albertel 1680:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1681:     $udom=$env{'user.domain'} unless (defined($udom));
                   1682:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1683:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1684:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1685: }
                   1686: 
                   1687: # ------------------------------------- Find the section of student in a course
1.652     albertel 1688: sub devalidate_getsection_cache {
                   1689:     my ($udom,$unam,$courseid)=@_;
                   1690:     my $hashid="$udom:$unam:$courseid";
                   1691:     &devalidate_cache_new('getsection',$hashid);
                   1692: }
1.298     matthew  1693: 
1.815     albertel 1694: sub courseid_to_courseurl {
                   1695:     my ($courseid) = @_;
                   1696:     #already url style courseid
                   1697:     return $courseid if ($courseid =~ m{^/});
                   1698: 
                   1699:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1700: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1701: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1702: 	return "/$cdom/$cnum";
                   1703:     }
                   1704: 
                   1705:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1706:     if (exists($courseinfo{'num'})) {
                   1707: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1708:     }
                   1709: 
                   1710:     return undef;
                   1711: }
                   1712: 
1.298     matthew  1713: sub getsection {
                   1714:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1715:     my $cachetime=1800;
1.551     albertel 1716: 
                   1717:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1718:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1719:     if (defined($cached)) { return $result; }
                   1720: 
1.298     matthew  1721:     my %Pending; 
                   1722:     my %Expired;
                   1723:     #
                   1724:     # Each role can either have not started yet (pending), be active, 
                   1725:     #    or have expired.
                   1726:     #
                   1727:     # If there is an active role, we are done.
                   1728:     #
                   1729:     # If there is more than one role which has not started yet, 
                   1730:     #     choose the one which will start sooner
                   1731:     # If there is one role which has not started yet, return it.
                   1732:     #
                   1733:     # If there is more than one expired role, choose the one which ended last.
                   1734:     # If there is a role which has expired, return it.
                   1735:     #
1.815     albertel 1736:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1737:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1738:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1739:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1740:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1741:         my $section=$1;
                   1742:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1743:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1744:         my $now=time;
1.548     albertel 1745:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1746:             $Expired{$end}=$section;
                   1747:             next;
                   1748:         }
1.548     albertel 1749:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1750:             $Pending{$start}=$section;
                   1751:             next;
                   1752:         }
1.599     albertel 1753:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1754:     }
                   1755:     #
                   1756:     # Presumedly there will be few matching roles from the above
                   1757:     # loop and the sorting time will be negligible.
                   1758:     if (scalar(keys(%Pending))) {
                   1759:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1760:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1761:     } 
                   1762:     if (scalar(keys(%Expired))) {
                   1763:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1764:         my $time = pop(@sorted);
1.599     albertel 1765:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1766:     }
1.599     albertel 1767:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1768: }
1.70      www      1769: 
1.599     albertel 1770: sub save_cache {
                   1771:     &purge_remembered();
1.722     albertel 1772:     #&Apache::loncommon::validate_page();
1.620     albertel 1773:     undef(%env);
1.780     albertel 1774:     undef($env_loaded);
1.599     albertel 1775: }
1.452     albertel 1776: 
1.599     albertel 1777: my $to_remember=-1;
                   1778: my %remembered;
                   1779: my %accessed;
                   1780: my $kicks=0;
                   1781: my $hits=0;
1.849     albertel 1782: sub make_key {
                   1783:     my ($name,$id) = @_;
1.872     albertel 1784:     if (length($id) > 65 
                   1785: 	&& length(&escape($id)) > 200) {
                   1786: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1787:     }
1.849     albertel 1788:     return &escape($name.':'.$id);
                   1789: }
                   1790: 
1.599     albertel 1791: sub devalidate_cache_new {
                   1792:     my ($name,$id,$debug) = @_;
                   1793:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1794:     $id=&make_key($name,$id);
1.599     albertel 1795:     $memcache->delete($id);
                   1796:     delete($remembered{$id});
                   1797:     delete($accessed{$id});
                   1798: }
                   1799: 
                   1800: sub is_cached_new {
                   1801:     my ($name,$id,$debug) = @_;
1.849     albertel 1802:     $id=&make_key($name,$id);
1.599     albertel 1803:     if (exists($remembered{$id})) {
                   1804: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1805: 	$accessed{$id}=[&gettimeofday()];
                   1806: 	$hits++;
                   1807: 	return ($remembered{$id},1);
                   1808:     }
                   1809:     my $value = $memcache->get($id);
                   1810:     if (!(defined($value))) {
                   1811: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1812: 	return (undef,undef);
1.416     albertel 1813:     }
1.599     albertel 1814:     if ($value eq '__undef__') {
                   1815: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1816: 	$value=undef;
                   1817:     }
                   1818:     &make_room($id,$value,$debug);
                   1819:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1820:     return ($value,1);
                   1821: }
                   1822: 
                   1823: sub do_cache_new {
                   1824:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1825:     $id=&make_key($name,$id);
1.599     albertel 1826:     my $setvalue=$value;
                   1827:     if (!defined($setvalue)) {
                   1828: 	$setvalue='__undef__';
                   1829:     }
1.623     albertel 1830:     if (!defined($time) ) {
                   1831: 	$time=600;
                   1832:     }
1.599     albertel 1833:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1834:     my $result = $memcache->set($id,$setvalue,$time);
                   1835:     if (! $result) {
1.872     albertel 1836: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1837: 	$memcache->disconnect_all();
1.872     albertel 1838:     }
1.600     albertel 1839:     # need to make a copy of $value
1.919     albertel 1840:     &make_room($id,$value,$debug);
1.599     albertel 1841:     return $value;
                   1842: }
                   1843: 
                   1844: sub make_room {
                   1845:     my ($id,$value,$debug)=@_;
1.919     albertel 1846: 
                   1847:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1848:                                     : $value;
1.599     albertel 1849:     if ($to_remember<0) { return; }
                   1850:     $accessed{$id}=[&gettimeofday()];
                   1851:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1852:     my $to_kick;
                   1853:     my $max_time=0;
                   1854:     foreach my $other (keys(%accessed)) {
                   1855: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1856: 	    $to_kick=$other;
                   1857: 	    $max_time=&tv_interval($accessed{$other});
                   1858: 	}
                   1859:     }
                   1860:     delete($remembered{$to_kick});
                   1861:     delete($accessed{$to_kick});
                   1862:     $kicks++;
                   1863:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1864:     return;
                   1865: }
                   1866: 
1.599     albertel 1867: sub purge_remembered {
1.604     albertel 1868:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1869:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1870:     undef(%remembered);
                   1871:     undef(%accessed);
1.428     albertel 1872: }
1.70      www      1873: # ------------------------------------- Read an entry from a user's environment
                   1874: 
                   1875: sub userenvironment {
                   1876:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1877:     my $items;
                   1878:     foreach my $item (@what) {
                   1879:         $items.=&escape($item).'&';
                   1880:     }
                   1881:     $items=~s/\&$//;
1.70      www      1882:     my %returnhash=();
1.1009    raeburn  1883:     my $uhome = &homeserver($unam,$udom);
                   1884:     unless ($uhome eq 'no_host') {
                   1885:         my @answer=split(/\&/, 
                   1886:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1887:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1888:             return %returnhash;
                   1889:         }
1.1009    raeburn  1890:         my $i;
                   1891:         for ($i=0;$i<=$#what;$i++) {
                   1892: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1893:         }
1.70      www      1894:     }
                   1895:     return %returnhash;
1.1       albertel 1896: }
                   1897: 
1.617     albertel 1898: # ---------------------------------------------------------- Get a studentphoto
                   1899: sub studentphoto {
                   1900:     my ($udom,$unam,$ext) = @_;
                   1901:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1902:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1903:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1904:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1905:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1906:             } else {
                   1907:                 my ($result,$perm_reqd)=
1.707     albertel 1908: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1909:                 if ($result eq 'ok') {
                   1910:                     if (!($perm_reqd eq 'yes')) {
                   1911:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1912:                     }
                   1913:                 }
                   1914:             }
                   1915:         }
                   1916:     } else {
                   1917:         my ($result,$perm_reqd) = 
1.707     albertel 1918: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1919:         if ($result eq 'ok') {
                   1920:             if (!($perm_reqd eq 'yes')) {
                   1921:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1922:             }
                   1923:         }
                   1924:     }
                   1925:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1926: }
                   1927: 
                   1928: sub retrievestudentphoto {
                   1929:     my ($udom,$unam,$ext,$type) = @_;
                   1930:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1931:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1932:     if ($ret eq 'ok') {
                   1933:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1934:         if ($type eq 'thumbnail') {
                   1935:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1936:         }
                   1937:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1938:         return $tokenurl;
                   1939:     } else {
                   1940:         if ($type eq 'thumbnail') {
                   1941:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1942:         } else { 
                   1943:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1944:         }
1.617     albertel 1945:     }
                   1946: }
                   1947: 
1.263     www      1948: # -------------------------------------------------------------------- New chat
                   1949: 
                   1950: sub chatsend {
1.724     raeburn  1951:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1952:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1953:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1954:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1955:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1956: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1957: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1958: }
                   1959: 
                   1960: # ------------------------------------------ Find current version of a resource
                   1961: 
                   1962: sub getversion {
                   1963:     my $fname=&clutter(shift);
                   1964:     unless ($fname=~/^\/res\//) { return -1; }
                   1965:     return &currentversion(&filelocation('',$fname));
                   1966: }
                   1967: 
                   1968: sub currentversion {
                   1969:     my $fname=shift;
1.599     albertel 1970:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1971:     if (defined($cached)) { return $result; }
1.292     www      1972:     my $author=$fname;
                   1973:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1974:     my ($udom,$uname)=split(/\//,$author);
                   1975:     my $home=homeserver($uname,$udom);
                   1976:     if ($home eq 'no_host') { 
                   1977:         return -1; 
                   1978:     }
                   1979:     my $answer=reply("currentversion:$fname",$home);
                   1980:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1981: 	return -1;
                   1982:     }
1.599     albertel 1983:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1984: }
                   1985: 
1.1       albertel 1986: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1987: 
1.1       albertel 1988: sub subscribe {
                   1989:     my $fname=shift;
1.761     raeburn  1990:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1991:     $fname=~s/[\n\r]//g;
1.1       albertel 1992:     my $author=$fname;
                   1993:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1994:     my ($udom,$uname)=split(/\//,$author);
                   1995:     my $home=homeserver($uname,$udom);
1.335     albertel 1996:     if ($home eq 'no_host') {
                   1997:         return 'not_found';
1.1       albertel 1998:     }
                   1999:     my $answer=reply("sub:$fname",$home);
1.64      www      2000:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2001: 	$answer.=' by '.$home;
                   2002:     }
1.1       albertel 2003:     return $answer;
                   2004: }
                   2005:     
1.8       www      2006: # -------------------------------------------------------------- Replicate file
                   2007: 
                   2008: sub repcopy {
                   2009:     my $filename=shift;
1.23      www      2010:     $filename=~s/\/+/\//g;
1.607     raeburn  2011:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2012:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2013:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2014: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2015: 	return &repcopy_userfile($filename);
                   2016:     }
1.532     albertel 2017:     $filename=~s/[\n\r]//g;
1.8       www      2018:     my $transname="$filename.in.transfer";
1.828     www      2019: # FIXME: this should flock
1.607     raeburn  2020:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2021:     my $remoteurl=subscribe($filename);
1.64      www      2022:     if ($remoteurl =~ /^con_lost by/) {
                   2023: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2024:            return 'unavailable';
1.8       www      2025:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2026: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2027: 	   return 'not_found';
1.64      www      2028:     } elsif ($remoteurl =~ /^rejected by/) {
                   2029: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2030:            return 'forbidden';
1.20      www      2031:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2032:            return 'ok';
1.8       www      2033:     } else {
1.290     www      2034:         my $author=$filename;
                   2035:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2036:         my ($udom,$uname)=split(/\//,$author);
                   2037:         my $home=homeserver($uname,$udom);
                   2038:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2039:            my @parts=split(/\//,$filename);
                   2040:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2041:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2042:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2043: 	       return 'bad_request';
1.8       www      2044:            }
                   2045:            my $count;
                   2046:            for ($count=5;$count<$#parts;$count++) {
                   2047:                $path.="/$parts[$count]";
                   2048:                if ((-e $path)!=1) {
                   2049: 		   mkdir($path,0777);
                   2050:                }
                   2051:            }
                   2052:            my $ua=new LWP::UserAgent;
                   2053:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2054:            my $response=$ua->request($request,$transname);
                   2055:            if ($response->is_error()) {
                   2056: 	       unlink($transname);
                   2057:                my $message=$response->status_line;
1.672     albertel 2058:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2059:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2060:                return 'unavailable';
1.8       www      2061:            } else {
1.16      www      2062: 	       if ($remoteurl!~/\.meta$/) {
                   2063:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2064:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2065:                   if ($mresponse->is_error()) {
                   2066: 		      unlink($filename.'.meta');
                   2067:                       &logthis(
1.672     albertel 2068:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2069:                   }
                   2070: 	       }
1.8       www      2071:                rename($transname,$filename);
1.607     raeburn  2072:                return 'ok';
1.8       www      2073:            }
1.290     www      2074:        }
1.8       www      2075:     }
1.330     www      2076: }
                   2077: 
                   2078: # ------------------------------------------------ Get server side include body
                   2079: sub ssi_body {
1.381     albertel 2080:     my ($filelink,%form)=@_;
1.606     matthew  2081:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2082:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2083:     }
1.953     www      2084:     my $output='';
                   2085:     my $response;
1.980     raeburn  2086:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2087:        ($output,$response)=&externalssi($filelink);
1.953     www      2088:     } else {
1.1004    droeschl 2089:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2090:        $filelink .= 'inhibitmenu=yes';
1.953     www      2091:        ($output,$response)=&ssi($filelink,%form);
                   2092:     }
1.778     albertel 2093:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2094:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2095:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2096:     if (wantarray) {
                   2097:         return ($output, $response);
                   2098:     } else {
                   2099:         return $output;
                   2100:     }
1.8       www      2101: }
                   2102: 
1.15      www      2103: # --------------------------------------------------------- Server Side Include
                   2104: 
1.782     albertel 2105: sub absolute_url {
                   2106:     my ($host_name) = @_;
                   2107:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2108:     if ($host_name eq '') {
                   2109: 	$host_name = $ENV{'SERVER_NAME'};
                   2110:     }
                   2111:     return $protocol.$host_name;
                   2112: }
                   2113: 
1.942     foxr     2114: #
                   2115: #   Server side include.
                   2116: # Parameters:
                   2117: #  fn     Possibly encrypted resource name/id.
                   2118: #  form   Hash that describes how the rendering should be done
                   2119: #         and other things.
1.944     foxr     2120: # Returns:
1.950     raeburn  2121: #   Scalar context: The content of the response.
                   2122: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2123: #     
1.15      www      2124: sub ssi {
                   2125: 
1.944     foxr     2126:     my ($fn,%form)=@_;
1.15      www      2127:     my $ua=new LWP::UserAgent;
1.23      www      2128:     my $request;
1.711     albertel 2129: 
                   2130:     $form{'no_update_last_known'}=1;
1.895     albertel 2131:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2132:     if (%form) {
1.782     albertel 2133:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2134:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2135:     } else {
1.782     albertel 2136:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2137:     }
                   2138: 
1.15      www      2139:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2140:     my $response=$ua->request($request);
                   2141: 
1.944     foxr     2142:     if (wantarray) {
                   2143: 	return ($response->content, $response);
                   2144:     } else {
                   2145: 	return $response->content;
1.942     foxr     2146:     }
1.324     www      2147: }
                   2148: 
                   2149: sub externalssi {
                   2150:     my ($url)=@_;
                   2151:     my $ua=new LWP::UserAgent;
                   2152:     my $request=new HTTP::Request('GET',$url);
                   2153:     my $response=$ua->request($request);
1.954     raeburn  2154:     if (wantarray) {
                   2155:         return ($response->content, $response);
                   2156:     } else {
                   2157:         return $response->content;
                   2158:     }
1.15      www      2159: }
1.254     www      2160: 
1.492     albertel 2161: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2162: 
                   2163: sub allowuploaded {
                   2164:     my ($srcurl,$url)=@_;
                   2165:     $url=&clutter(&declutter($url));
                   2166:     my $dir=$url;
                   2167:     $dir=~s/\/[^\/]+$//;
                   2168:     my %httpref=();
                   2169:     my $httpurl=&hreflocation('',$url);
                   2170:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2171:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2172: }
1.477     raeburn  2173: 
1.478     albertel 2174: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2175: # input: action, courseID, current domain, intended
1.637     raeburn  2176: #        path to file, source of file, instruction to parse file for objects,
                   2177: #        ref to hash for embedded objects,
                   2178: #        ref to hash for codebase of java objects.
                   2179: #
1.485     raeburn  2180: # output: url to file (if action was uploaddoc), 
                   2181: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2182: #
1.478     albertel 2183: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2184: # course.
1.477     raeburn  2185: #
1.478     albertel 2186: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2187: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2188: #          course's home server.
1.477     raeburn  2189: #
1.478     albertel 2190: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2191: #          be copied from $source (current location) to 
                   2192: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2193: #         and will then be copied to
                   2194: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2195: #         course's home server.
1.485     raeburn  2196: #
1.481     raeburn  2197: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2198: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2199: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2200: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2201: #         in course's home server.
1.637     raeburn  2202: #
1.477     raeburn  2203: 
                   2204: sub process_coursefile {
1.638     albertel 2205:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2206:     my $fetchresult;
1.638     albertel 2207:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2208:     if ($action eq 'propagate') {
1.638     albertel 2209:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2210: 			     $home);
1.481     raeburn  2211:     } else {
1.477     raeburn  2212:         my $fpath = '';
                   2213:         my $fname = $file;
1.478     albertel 2214:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2215:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2216:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2217:         if ($action eq 'copy') {
                   2218:             if ($source eq '') {
                   2219:                 $fetchresult = 'no source file';
                   2220:                 return $fetchresult;
                   2221:             } else {
                   2222:                 my $destination = $filepath.'/'.$fname;
                   2223:                 rename($source,$destination);
                   2224:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2225:                                  $home);
1.481     raeburn  2226:             }
                   2227:         } elsif ($action eq 'uploaddoc') {
                   2228:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2229:             print $fh $env{'form.'.$source};
1.481     raeburn  2230:             close($fh);
1.637     raeburn  2231:             if ($parser eq 'parse') {
1.1024    raeburn  2232:                 my $mm = new File::MMagic;
                   2233:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2234:                 if ($mime_type eq 'text/html') {
                   2235:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2236:                     unless ($parse_result eq 'ok') {
                   2237:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2238:                     }
1.637     raeburn  2239:                 }
                   2240:             }
1.477     raeburn  2241:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2242:                                  $home);
1.481     raeburn  2243:             if ($fetchresult eq 'ok') {
                   2244:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2245:             } else {
                   2246:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2247:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2248:                 return '/adm/notfound.html';
                   2249:             }
1.477     raeburn  2250:         }
                   2251:     }
1.485     raeburn  2252:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2253:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2254:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2255:     }
                   2256:     return $fetchresult;
                   2257: }
                   2258: 
1.637     raeburn  2259: sub build_filepath {
                   2260:     my ($fpath) = @_;
                   2261:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2262:     unless ($fpath eq '') {
                   2263:         my @parts=split('/',$fpath);
                   2264:         foreach my $part (@parts) {
                   2265:             $filepath.= '/'.$part;
                   2266:             if ((-e $filepath)!=1) {
                   2267:                 mkdir($filepath,0777);
                   2268:             }
                   2269:         }
                   2270:     }
                   2271:     return $filepath;
                   2272: }
                   2273: 
                   2274: sub store_edited_file {
1.638     albertel 2275:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2276:     my $file = $primary_url;
                   2277:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2278:     my $fpath = '';
                   2279:     my $fname = $file;
                   2280:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2281:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2282:     my $filepath = &build_filepath($fpath);
                   2283:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2284:     print $fh $content;
                   2285:     close($fh);
1.638     albertel 2286:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2287:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2288: 			  $home);
1.637     raeburn  2289:     if ($$fetchresult eq 'ok') {
                   2290:         return '/uploaded/'.$fpath.'/'.$fname;
                   2291:     } else {
1.638     albertel 2292:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2293: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2294:         return '/adm/notfound.html';
                   2295:     }
                   2296: }
                   2297: 
1.531     albertel 2298: sub clean_filename {
1.831     albertel 2299:     my ($fname,$args)=@_;
1.315     www      2300: # Replace Windows backslashes by forward slashes
1.257     www      2301:     $fname=~s/\\/\//g;
1.831     albertel 2302:     if (!$args->{'keep_path'}) {
                   2303:         # Get rid of everything but the actual filename
                   2304: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2305:     }
1.315     www      2306: # Replace spaces by underscores
                   2307:     $fname=~s/\s+/\_/g;
                   2308: # Replace all other weird characters by nothing
1.831     albertel 2309:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2310: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2311: # numbers
                   2312:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2313:     return $fname;
                   2314: }
1.1051    raeburn  2315: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2316: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2317: # image with the same aspect ratio as the original, but with dimensions which do 
                   2318: # not exceed $resizewidth and $resizeheight.
                   2319:  
1.984     neumanie 2320: sub resizeImage {
1.1051    raeburn  2321:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2322:     my $ima = Image::Magick->new;
                   2323:     my $resized;
                   2324:     if (-e $img_path) {
                   2325:         $ima->Read($img_path);
                   2326:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2327:             my $width = $ima->Get('width');
                   2328:             my $height = $ima->Get('height');
                   2329:             if ($width > $resizewidth) {
                   2330: 	        my $factor = $width/$resizewidth;
                   2331:                 my $newheight = $height/$factor;
                   2332:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2333:                 $resized = 1;
                   2334:             }
                   2335:         }
                   2336:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2337:             my $width = $ima->Get('width');
                   2338:             my $height = $ima->Get('height');
                   2339:             if ($height > $resizeheight) {
                   2340:                 my $factor = $height/$resizeheight;
                   2341:                 my $newwidth = $width/$factor;
                   2342:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2343:                 $resized = 1;
                   2344:             }
                   2345:         }
                   2346:         if ($resized) {
                   2347:             $ima->Write($img_path);
                   2348:         }
                   2349:     }
                   2350:     return;
1.977     amueller 2351: }
                   2352: 
1.608     albertel 2353: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2354: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2355: #                    the desired filenam is in $env{"form.$formname.filename"}
1.1090  ! raeburn  2356: #        $context - possible values: coursedoc, existingfile, overwrite, 
        !          2357: #                                    canceloverwrite, or ''. 
        !          2358: #                   if 'coursedoc': upload to the current course
        !          2359: #                   if 'existingfile': write file to tmp/overwrites directory 
        !          2360: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
        !          2361: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2362: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2363: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2364: #        $allfiles - reference to hash for embedded objects
                   2365: #        $codebase - reference to hash for codebase of java objects
                   2366: #        $desuname - username for permanent storage of uploaded file
                   2367: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2368: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2369: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2370: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2371: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2372: # 
1.686     albertel 2373: # output: url of file in userspace, or error: <message> 
                   2374: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2375: 
1.531     albertel 2376: sub userfileupload {
1.1090  ! raeburn  2377:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2378:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2379:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2380:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2381:     $fname=&clean_filename($fname);
1.1090  ! raeburn  2382:     # See if there is anything left
1.257     www      2383:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2384:     chop($env{'form.'.$formname});
1.1090  ! raeburn  2385:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
        !          2386:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
        !          2387:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
        !          2388:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2389:         my $now = time;
1.1090  ! raeburn  2390:         my $filepath;
        !          2391:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { 
        !          2392:              $filepath = 'tmp/helprequests/'.$now;
        !          2393:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
        !          2394:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
        !          2395:                          '_'.$env{'user.domain'}.'/pending';
        !          2396:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
        !          2397:             my ($docuname,$docudom);
        !          2398:             if ($destudom) {
        !          2399:                 $docudom = $destudom;
        !          2400:             } else {
        !          2401:                 $docudom = $env{'user.domain'};
        !          2402:             }
        !          2403:             if ($destuname) {
        !          2404:                 $docuname = $destuname;
        !          2405:             } else {
        !          2406:                 $docuname = $env{'user.name'};
        !          2407:             }
        !          2408:             if (exists($env{'form.group'})) {
        !          2409:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
        !          2410:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
        !          2411:             }
        !          2412:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
        !          2413:             if ($context eq 'canceloverwrite') {
        !          2414:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
        !          2415:                 if (-e  $tempfile) {
        !          2416:                     my @info = stat($tempfile);
        !          2417:                     if ($info[9] eq $env{'form.timestamp'}) {
        !          2418:                         unlink($tempfile);
        !          2419:                     }
        !          2420:                 }
        !          2421:                 return;
1.523     raeburn  2422:             }
                   2423:         }
1.1090  ! raeburn  2424:         # Create the directory if not present
1.741     raeburn  2425:         my @parts=split(/\//,$filepath);
                   2426:         my $fullpath = $perlvar{'lonDaemons'};
                   2427:         for (my $i=0;$i<@parts;$i++) {
                   2428:             $fullpath .= '/'.$parts[$i];
                   2429:             if ((-e $fullpath)!=1) {
                   2430:                 mkdir($fullpath,0777);
                   2431:             }
                   2432:         }
                   2433:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2434:         print $fh $env{'form.'.$formname};
                   2435:         close($fh);
1.1090  ! raeburn  2436:         if ($context eq 'existingfile') {
        !          2437:             my @info = stat($fullpath.'/'.$fname);
        !          2438:             return ($fullpath.'/'.$fname,$info[9]);
        !          2439:         } else {
        !          2440:             return $fullpath.'/'.$fname;
        !          2441:         }
1.523     raeburn  2442:     }
1.995     raeburn  2443:     if ($subdir eq 'scantron') {
                   2444:         $fname = 'scantron_orig_'.$fname;
                   2445:     } else {   
                   2446:         $fname="$subdir/$fname";
                   2447:     }
1.1090  ! raeburn  2448:     if ($context eq 'coursedoc') {
1.638     albertel 2449: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2450: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2451:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2452:             return &finishuserfileupload($docuname,$docudom,
                   2453: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2454: 					 $codebase,$thumbwidth,$thumbheight,
1.1090  ! raeburn  2455:                                          $resizewidth,$resizeheight,$context);
1.481     raeburn  2456:         } else {
1.620     albertel 2457:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2458:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2459: 				       $fname,$formname,$parser,
                   2460: 				       $allfiles,$codebase);
1.481     raeburn  2461:         }
1.719     banghart 2462:     } elsif (defined($destuname)) {
                   2463:         my $docuname=$destuname;
                   2464:         my $docudom=$destudom;
1.860     raeburn  2465: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2466: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2467:                                      $thumbwidth,$thumbheight,
1.1090  ! raeburn  2468:                                      $resizewidth,$resizeheight,$context);
1.259     www      2469:     } else {
1.638     albertel 2470:         my $docuname=$env{'user.name'};
                   2471:         my $docudom=$env{'user.domain'};
1.714     raeburn  2472:         if (exists($env{'form.group'})) {
                   2473:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2474:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2475:         }
1.860     raeburn  2476: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2477: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2478:                                      $thumbwidth,$thumbheight,
1.1090  ! raeburn  2479:                                      $resizewidth,$resizeheight,$context);
1.259     www      2480:     }
1.271     www      2481: }
                   2482: 
                   2483: sub finishuserfileupload {
1.860     raeburn  2484:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1090  ! raeburn  2485:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context) = @_;
1.477     raeburn  2486:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2487:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2488:   
1.860     raeburn  2489:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2490:     $file=$fname;
                   2491:     if ($fname=~m|/|) {
                   2492:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2493: 	$path.=$fnamepath.'/';
                   2494:     }
1.259     www      2495:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2496:     my $count;
                   2497:     for ($count=4;$count<=$#parts;$count++) {
                   2498:         $filepath.="/$parts[$count]";
                   2499:         if ((-e $filepath)!=1) {
                   2500: 	    mkdir($filepath,0777);
                   2501:         }
                   2502:     }
1.984     neumanie 2503: 
1.258     www      2504: # Save the file
                   2505:     {
1.701     albertel 2506: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2507: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2508: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2509: 	    return '/adm/notfound.html';
                   2510: 	}
1.1090  ! raeburn  2511:         if ($context eq 'overwrite') {
        !          2512:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
        !          2513:             my $target = $filepath.'/'.$file;
        !          2514:             if (-e $source) {
        !          2515:                 my @info = stat($source);
        !          2516:                 if ($info[9] eq $env{'form.timestamp'}) {   
        !          2517:                     unless (&File::Copy::move($source,$target)) {
        !          2518:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
        !          2519:                         return "Moving from $source failed";
        !          2520:                     }
        !          2521:                 } else {
        !          2522:                     return "Temporary file: $source had unexpected date/time for last modification";
        !          2523:                 }
        !          2524:             } else {
        !          2525:                 return "Temporary file: $source missing";
        !          2526:             }
        !          2527:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2528: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2529: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2530: 	    return '/adm/notfound.html';
                   2531: 	}
1.570     albertel 2532: 	close(FH);
1.1051    raeburn  2533:         if ($resizewidth && $resizeheight) {
                   2534:             my $mm = new File::MMagic;
                   2535:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2536:             if ($mime_type =~ m{^image/}) {
                   2537: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2538:             }  
1.977     amueller 2539: 	}
1.258     www      2540:     }
1.637     raeburn  2541:     if ($parser eq 'parse') {
1.1024    raeburn  2542:         my $mm = new File::MMagic;
                   2543:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2544:         if ($mime_type eq 'text/html') {
                   2545:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2546:                                                        $allfiles,$codebase);
                   2547:             unless ($parse_result eq 'ok') {
                   2548:                 &logthis('Failed to parse '.$filepath.$file.
                   2549: 	   	         ' for embedded media: '.$parse_result); 
                   2550:             }
1.637     raeburn  2551:         }
                   2552:     }
1.860     raeburn  2553:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2554:         my $input = $filepath.'/'.$file;
                   2555:         my $output = $filepath.'/'.'tn-'.$file;
                   2556:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2557:         system("convert -sample $thumbsize $input $output");
                   2558:         if (-e $filepath.'/'.'tn-'.$file) {
                   2559:             $fetchthumb  = 1; 
                   2560:         }
                   2561:     }
1.858     raeburn  2562:  
1.259     www      2563: # Notify homeserver to grep it
                   2564: #
1.984     neumanie 2565:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2566:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2567:     if ($fetchresult eq 'ok') {
1.860     raeburn  2568:         if ($fetchthumb) {
                   2569:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2570:             if ($thumbresult ne 'ok') {
                   2571:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2572:                          $docuhome.': '.$thumbresult);
                   2573:             }
                   2574:         }
1.259     www      2575: #
1.258     www      2576: # Return the URL to it
1.494     albertel 2577:         return '/uploaded/'.$path.$file;
1.263     www      2578:     } else {
1.494     albertel 2579:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2580: 		 ': '.$fetchresult);
1.263     www      2581:         return '/adm/notfound.html';
1.858     raeburn  2582:     }
1.493     albertel 2583: }
                   2584: 
1.637     raeburn  2585: sub extract_embedded_items {
1.961     raeburn  2586:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2587:     my @state = ();
                   2588:     my %javafiles = (
                   2589:                       codebase => '',
                   2590:                       code => '',
                   2591:                       archive => ''
                   2592:                     );
                   2593:     my %mediafiles = (
                   2594:                       src => '',
                   2595:                       movie => '',
                   2596:                      );
1.648     raeburn  2597:     my $p;
                   2598:     if ($content) {
                   2599:         $p = HTML::LCParser->new($content);
                   2600:     } else {
1.961     raeburn  2601:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2602:     }
1.641     albertel 2603:     while (my $t=$p->get_token()) {
1.640     albertel 2604: 	if ($t->[0] eq 'S') {
                   2605: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2606: 	    push(@state, $tagname);
1.648     raeburn  2607:             if (lc($tagname) eq 'allow') {
                   2608:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2609:             }
1.640     albertel 2610: 	    if (lc($tagname) eq 'img') {
                   2611: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2612: 	    }
1.886     albertel 2613: 	    if (lc($tagname) eq 'a') {
                   2614: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2615: 	    }
1.645     raeburn  2616:             if (lc($tagname) eq 'script') {
                   2617:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2618:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2619:                 } else {
                   2620:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2621:                 }
                   2622:             }
                   2623:             if (lc($tagname) eq 'link') {
                   2624:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2625:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2626:                 }
                   2627:             }
1.640     albertel 2628: 	    if (lc($tagname) eq 'object' ||
                   2629: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2630: 		foreach my $item (keys(%javafiles)) {
                   2631: 		    $javafiles{$item} = '';
                   2632: 		}
                   2633: 	    }
                   2634: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2635: 		my $name = lc($attr->{'name'});
                   2636: 		foreach my $item (keys(%javafiles)) {
                   2637: 		    if ($name eq $item) {
                   2638: 			$javafiles{$item} = $attr->{'value'};
                   2639: 			last;
                   2640: 		    }
                   2641: 		}
                   2642: 		foreach my $item (keys(%mediafiles)) {
                   2643: 		    if ($name eq $item) {
                   2644: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2645: 			last;
                   2646: 		    }
                   2647: 		}
                   2648: 	    }
                   2649: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2650: 		foreach my $item (keys(%javafiles)) {
                   2651: 		    if ($attr->{$item}) {
                   2652: 			$javafiles{$item} = $attr->{$item};
                   2653: 			last;
                   2654: 		    }
                   2655: 		}
                   2656: 		foreach my $item (keys(%mediafiles)) {
                   2657: 		    if ($attr->{$item}) {
                   2658: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2659: 			last;
                   2660: 		    }
                   2661: 		}
                   2662: 	    }
                   2663: 	} elsif ($t->[0] eq 'E') {
                   2664: 	    my ($tagname) = ($t->[1]);
                   2665: 	    if ($javafiles{'codebase'} ne '') {
                   2666: 		$javafiles{'codebase'} .= '/';
                   2667: 	    }  
                   2668: 	    if (lc($tagname) eq 'applet' ||
                   2669: 		lc($tagname) eq 'object' ||
                   2670: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2671: 		) {
                   2672: 		foreach my $item (keys(%javafiles)) {
                   2673: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2674: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2675: 			&add_filetype($allfiles,$file,$item);
                   2676: 		    }
                   2677: 		}
                   2678: 	    } 
                   2679: 	    pop @state;
                   2680: 	}
                   2681:     }
1.637     raeburn  2682:     return 'ok';
                   2683: }
                   2684: 
1.639     albertel 2685: sub add_filetype {
                   2686:     my ($allfiles,$file,$type)=@_;
                   2687:     if (exists($allfiles->{$file})) {
                   2688: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2689: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2690: 	}
                   2691:     } else {
                   2692: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2693:     }
                   2694: }
                   2695: 
1.493     albertel 2696: sub removeuploadedurl {
1.984     neumanie 2697:     my ($url)=@_;	
                   2698:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2699:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2700: }
                   2701: 
                   2702: sub removeuserfile {
                   2703:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2704:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2705:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2706:     if ($result eq 'ok') {	
1.798     raeburn  2707:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2708:             my $metafile = $fname.'.meta';
                   2709:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2710: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2711:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2712:             my $sqlresult = 
1.823     albertel 2713:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2714:                                         'portfolio_metadata',$group,
                   2715:                                         'delete');
1.798     raeburn  2716:         }
                   2717:     }
                   2718:     return $result;
1.257     www      2719: }
1.15      www      2720: 
1.530     albertel 2721: sub mkdiruserfile {
                   2722:     my ($docuname,$docudom,$dir)=@_;
                   2723:     my $home=&homeserver($docuname,$docudom);
                   2724:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2725: }
                   2726: 
1.531     albertel 2727: sub renameuserfile {
                   2728:     my ($docuname,$docudom,$old,$new)=@_;
                   2729:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2730:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2731:                         &escape("$old").':'.&escape("$new"),$home);
                   2732:     if ($result eq 'ok') {
                   2733:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2734:             my $oldmeta = $old.'.meta';
                   2735:             my $newmeta = $new.'.meta';
                   2736:             my $metaresult = 
                   2737:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2738: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2739:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2740:             my $sqlresult = 
1.823     albertel 2741:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2742:                                         'portfolio_metadata',$group,
                   2743:                                         'delete');
1.798     raeburn  2744:         }
                   2745:     }
                   2746:     return $result;
1.531     albertel 2747: }
                   2748: 
1.14      www      2749: # ------------------------------------------------------------------------- Log
                   2750: 
                   2751: sub log {
                   2752:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2753:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2754: }
                   2755: 
                   2756: # ------------------------------------------------------------------ Course Log
1.352     www      2757: #
                   2758: # This routine flushes several buffers of non-mission-critical nature
                   2759: #
1.157     www      2760: 
                   2761: sub flushcourselogs {
1.352     www      2762:     &logthis('Flushing log buffers');
                   2763: #
                   2764: # course logs
                   2765: # This is a log of all transactions in a course, which can be used
                   2766: # for data mining purposes
                   2767: #
                   2768: # It also collects the courseid database, which lists last transaction
                   2769: # times and course titles for all courseids
                   2770: #
                   2771:     my %courseidbuffer=();
1.921     raeburn  2772:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2773:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2774: 		          &escape($courselogs{$crsid}),
                   2775: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2776: 	    delete $courselogs{$crsid};
                   2777:         } else {
                   2778:             &logthis('Failed to flush log buffer for '.$crsid);
                   2779:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2780:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2781:                         " exceeded maximum size, deleting.</font>");
                   2782:                delete $courselogs{$crsid};
                   2783:             }
1.352     www      2784:         }
1.920     raeburn  2785:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2786:             'description' => $coursedescrbuf{$crsid},
                   2787:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2788:             'type'        => $coursetypebuf{$crsid},
                   2789:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2790:         };
1.191     harris41 2791:     }
1.352     www      2792: #
                   2793: # Write course id database (reverse lookup) to homeserver of courses 
                   2794: # Is used in pickcourse
                   2795: #
1.840     albertel 2796:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2797:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2798:                                     $courseidbuffer{$crs_home},
                   2799:                                     $crs_home,'timeonly');
1.352     www      2800:     }
                   2801: #
                   2802: # File accesses
                   2803: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2804: #
1.449     matthew  2805:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2806:         if ($entry =~ /___count$/) {
                   2807:             my ($dom,$name);
1.807     albertel 2808:             ($dom,$name,undef)=
1.811     albertel 2809: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2810:             if (! defined($dom) || $dom eq '' || 
                   2811:                 ! defined($name) || $name eq '') {
1.620     albertel 2812:                 my $cid = $env{'request.course.id'};
                   2813:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2814:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2815:             }
1.450     matthew  2816:             my $value = $accesshash{$entry};
                   2817:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2818:             my %temphash=($url => $value);
1.449     matthew  2819:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2820:             if ($result eq 'ok') {
                   2821:                 delete $accesshash{$entry};
                   2822:             } elsif ($result eq 'unknown_cmd') {
                   2823:                 # Target server has old code running on it.
1.450     matthew  2824:                 my %temphash=($entry => $value);
1.449     matthew  2825:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2826:                     delete $accesshash{$entry};
                   2827:                 }
                   2828:             }
                   2829:         } else {
1.811     albertel 2830:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2831:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2832:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2833:                 delete $accesshash{$entry};
                   2834:             }
1.185     www      2835:         }
1.191     harris41 2836:     }
1.352     www      2837: #
                   2838: # Roles
                   2839: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2840: #
1.800     albertel 2841:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2842:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2843: 	    split(/\:/,$entry);
                   2844:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2845:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2846:                 $rudom,$runame) eq 'ok') {
                   2847: 	    delete $userrolehash{$entry};
                   2848:         }
                   2849:     }
1.662     raeburn  2850: #
                   2851: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2852: #
                   2853:     my %domrolebuffer = ();
1.1000    raeburn  2854:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2855:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2856:         if ($domrolebuffer{$rudom}) {
                   2857:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2858:                       '='.&escape($domainrolehash{$entry});
                   2859:         } else {
                   2860:             $domrolebuffer{$rudom}.=&escape($entry).
                   2861:                       '='.&escape($domainrolehash{$entry});
                   2862:         }
                   2863:         delete $domainrolehash{$entry};
                   2864:     }
                   2865:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2866: 	my %servers = &get_servers($dom,'library');
                   2867: 	foreach my $tryserver (keys(%servers)) {
                   2868: 	    unless (&reply('domroleput:'.$dom.':'.
                   2869: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2870: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2871: 	    }
1.662     raeburn  2872:         }
                   2873:     }
1.186     www      2874:     $dumpcount++;
1.157     www      2875: }
                   2876: 
                   2877: sub courselog {
                   2878:     my $what=shift;
1.158     www      2879:     $what=time.':'.$what;
1.620     albertel 2880:     unless ($env{'request.course.id'}) { return ''; }
                   2881:     $coursedombuf{$env{'request.course.id'}}=
                   2882:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2883:     $coursenumbuf{$env{'request.course.id'}}=
                   2884:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2885:     $coursehombuf{$env{'request.course.id'}}=
                   2886:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2887:     $coursedescrbuf{$env{'request.course.id'}}=
                   2888:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2889:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2890:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2891:     $courseownerbuf{$env{'request.course.id'}}=
                   2892:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2893:     $coursetypebuf{$env{'request.course.id'}}=
                   2894:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2895:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2896: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2897:     } else {
1.620     albertel 2898: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2899:     }
1.620     albertel 2900:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2901: 	&flushcourselogs();
                   2902:     }
1.158     www      2903: }
                   2904: 
                   2905: sub courseacclog {
                   2906:     my $fnsymb=shift;
1.620     albertel 2907:     unless ($env{'request.course.id'}) { return ''; }
                   2908:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2909:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2910:         $what.=':POST';
1.583     matthew  2911:         # FIXME: Probably ought to escape things....
1.800     albertel 2912: 	foreach my $key (keys(%env)) {
                   2913:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2914:                 my $formitem = $1;
                   2915:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2916:                     $what.=':'.$formitem.'='.$env{$key};
                   2917:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2918:                     $what.=':'.$formitem.'='.$env{$key};
                   2919:                 }
1.158     www      2920:             }
1.191     harris41 2921:         }
1.583     matthew  2922:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2923:         # FIXME: We should not be depending on a form parameter that someone
                   2924:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2925:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2926:             $what.= ':POST';
                   2927:             # FIXME: Probably ought to escape things....
                   2928:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2929:                                  'crsdiscuss') {
1.620     albertel 2930:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2931:             }
                   2932:         }
1.158     www      2933:     }
                   2934:     &courselog($what);
1.149     www      2935: }
                   2936: 
1.185     www      2937: sub countacc {
                   2938:     my $url=&declutter(shift);
1.458     matthew  2939:     return if (! defined($url) || $url eq '');
1.620     albertel 2940:     unless ($env{'request.course.id'}) { return ''; }
                   2941:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2942:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2943:     $accesshash{$key}++;
1.185     www      2944: }
1.349     www      2945: 
1.361     www      2946: sub linklog {
                   2947:     my ($from,$to)=@_;
                   2948:     $from=&declutter($from);
                   2949:     $to=&declutter($to);
                   2950:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2951:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2952: }
                   2953:   
1.349     www      2954: sub userrolelog {
                   2955:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2956:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2957:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2958:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2959:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2961:        $userrolehash
                   2962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2963:                     =$tend.':'.$tstart;
1.662     raeburn  2964:     }
1.898     albertel 2965:     if (($env{'request.role'} =~ /dc\./) &&
                   2966: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2967: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2968: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2969:          ($trole=~/^co/))) {
1.898     albertel 2970:        $userrolehash
                   2971:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2972:                     =$tend.':'.$tstart;
                   2973:     }
1.662     raeburn  2974:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2975:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2976:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2977:         ($trole=~/^sc/)) {
                   2978:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2979:        $domainrolehash
                   2980:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2981:                     = $tend.':'.$tstart;
                   2982:     }
1.351     www      2983: }
                   2984: 
1.957     raeburn  2985: sub courserolelog {
                   2986:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2987:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2988:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2989:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2990:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2991:         ($trole eq 'co')) {
1.957     raeburn  2992:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2993:             my $cdom = $1;
                   2994:             my $cnum = $2;
                   2995:             my $sec = $3;
                   2996:             my $namespace = 'rolelog';
                   2997:             my %storehash = (
                   2998:                                role    => $trole,
                   2999:                                start   => $tstart,
                   3000:                                end     => $tend,
                   3001:                                selfenroll => $selfenroll,
                   3002:                                context    => $context,
                   3003:                             );
                   3004:             if ($trole eq 'gr') {
                   3005:                 $namespace = 'groupslog';
                   3006:                 $storehash{'group'} = $sec;
                   3007:             } else {
                   3008:                 $storehash{'section'} = $sec;
                   3009:             }
                   3010:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3011:             if (($trole ne 'st') || ($sec ne '')) {
                   3012:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3013:             }
1.957     raeburn  3014:         }
                   3015:     }
                   3016:     return;
                   3017: }
                   3018: 
1.351     www      3019: sub get_course_adv_roles {
1.948     raeburn  3020:     my ($cid,$codes) = @_;
1.620     albertel 3021:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3022:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3023:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3024:     my %nothide=();
1.800     albertel 3025:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3026:         if ($user !~ /:/) {
                   3027: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3028:         } else {
                   3029:             $nothide{$user}=1;
                   3030:         }
1.470     www      3031:     }
1.351     www      3032:     my %returnhash=();
                   3033:     my %dumphash=
                   3034:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3035:     my $now=time;
1.997     raeburn  3036:     my %privileged;
1.1000    raeburn  3037:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3038: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3039:         if (($tstart) && ($tstart<0)) { next; }
                   3040:         if (($tend) && ($tend<$now)) { next; }
                   3041:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3042:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3043: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3044:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3045:             my %dompersonnel =
1.998     raeburn  3046:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3047:             $privileged{$domain} = {};
                   3048:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3049:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3050:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3051:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3052:                         $privileged{$udom}{$uname} = 1;
                   3053:                     }
                   3054:                 }
                   3055:             }
                   3056:         }
                   3057:         if ((exists($privileged{$domain}{$username})) && 
                   3058:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3059: 	if ($role eq 'cr') { next; }
1.948     raeburn  3060:         if ($codes) {
                   3061:             if ($section) { $role .= ':'.$section; }
                   3062:             if ($returnhash{$role}) {
                   3063:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3064:             } else {
                   3065:                 $returnhash{$role}=$username.':'.$domain;
                   3066:             }
1.351     www      3067:         } else {
1.988     raeburn  3068:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3069:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3070:             if ($returnhash{$key}) {
                   3071: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3072:             } else {
                   3073:                 $returnhash{$key}=$username.':'.$domain;
                   3074:             }
1.351     www      3075:         }
1.948     raeburn  3076:     }
1.400     www      3077:     return %returnhash;
                   3078: }
                   3079: 
                   3080: sub get_my_roles {
1.937     raeburn  3081:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3082:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3083:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3084:     my (%dumphash,%nothide);
1.1086    raeburn  3085:     if ($context eq 'userroles') {
                   3086:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3087:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3088:     } else {
                   3089:         %dumphash=
1.400     www      3090:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3091:         if ($hidepriv) {
                   3092:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3093:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3094:                 if ($user !~ /:/) {
                   3095:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3096:                 } else {
                   3097:                     $nothide{$user} = 1;
                   3098:                 }
                   3099:             }
                   3100:         }
1.858     raeburn  3101:     }
1.400     www      3102:     my %returnhash=();
                   3103:     my $now=time;
1.999     raeburn  3104:     my %privileged;
1.800     albertel 3105:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3106:         my ($role,$tend,$tstart);
                   3107:         if ($context eq 'userroles') {
                   3108: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3109:         } else {
                   3110:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3111:         }
1.400     www      3112:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3113:         my $status = 'active';
1.939     raeburn  3114:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3115:             $status = 'previous';
                   3116:         } 
                   3117:         if (($tstart) && ($now<$tstart)) {
                   3118:             $status = 'future';
                   3119:         }
                   3120:         if (ref($types) eq 'ARRAY') {
                   3121:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3122:                 next;
                   3123:             } 
                   3124:         } else {
                   3125:             if ($status ne 'active') {
                   3126:                 next;
                   3127:             }
                   3128:         }
1.867     raeburn  3129:         my ($rolecode,$username,$domain,$section,$area);
                   3130:         if ($context eq 'userroles') {
                   3131:             ($area,$rolecode) = split(/_/,$entry);
                   3132:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3133:         } else {
                   3134:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3135:         }
1.832     raeburn  3136:         if (ref($roledoms) eq 'ARRAY') {
                   3137:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3138:                 next;
                   3139:             }
                   3140:         }
                   3141:         if (ref($roles) eq 'ARRAY') {
                   3142:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3143:                 if ($role =~ /^cr\//) {
                   3144:                     if (!grep(/^cr$/,@{$roles})) {
                   3145:                         next;
                   3146:                     }
                   3147:                 } else {
                   3148:                     next;
                   3149:                 }
1.832     raeburn  3150:             }
1.867     raeburn  3151:         }
1.937     raeburn  3152:         if ($hidepriv) {
1.999     raeburn  3153:             if ($context eq 'userroles') {
                   3154:                 if ((&privileged($username,$domain)) &&
                   3155:                     (!$nothide{$username.':'.$domain})) {
                   3156:                     next;
                   3157:                 }
                   3158:             } else {
                   3159:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3160:                     my %dompersonnel =
                   3161:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3162:                     $privileged{$domain} = {};
                   3163:                     if (keys(%dompersonnel)) {
                   3164:                         foreach my $server (keys(%dompersonnel)) {
                   3165:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3166:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3167:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3168:                                     $privileged{$udom}{$uname} = $trole;
                   3169:                                 }
                   3170:                             }
                   3171:                         }
                   3172:                     }
                   3173:                 }
                   3174:                 if (exists($privileged{$domain}{$username})) {
                   3175:                     if (!$nothide{$username.':'.$domain}) {
                   3176:                         next;
                   3177:                     }
                   3178:                 }
1.937     raeburn  3179:             }
                   3180:         }
1.933     raeburn  3181:         if ($withsec) {
                   3182:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3183:                 $tstart.':'.$tend;
                   3184:         } else {
                   3185:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3186:         }
1.832     raeburn  3187:     }
1.373     www      3188:     return %returnhash;
1.399     www      3189: }
                   3190: 
                   3191: # ----------------------------------------------------- Frontpage Announcements
                   3192: #
                   3193: #
                   3194: 
                   3195: sub postannounce {
                   3196:     my ($server,$text)=@_;
1.844     albertel 3197:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3198:     unless ($text=~/\w/) { $text=''; }
                   3199:     return &reply('setannounce:'.&escape($text),$server);
                   3200: }
                   3201: 
                   3202: sub getannounce {
1.448     albertel 3203: 
                   3204:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3205: 	my $announcement='';
1.800     albertel 3206: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3207: 	close($fh);
1.399     www      3208: 	if ($announcement=~/\w/) { 
                   3209: 	    return 
                   3210:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3211:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3212: 	} else {
                   3213: 	    return '';
                   3214: 	}
                   3215:     } else {
                   3216: 	return '';
                   3217:     }
1.351     www      3218: }
1.353     www      3219: 
                   3220: # ---------------------------------------------------------- Course ID routines
                   3221: # Deal with domain's nohist_courseid.db files
                   3222: #
                   3223: 
                   3224: sub courseidput {
1.921     raeburn  3225:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3226:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3227:     my $outcome;
                   3228:     if ($caller eq 'timeonly') {
                   3229:         my $cids = '';
                   3230:         foreach my $item (keys(%$storehash)) {
                   3231:             $cids.=&escape($item).'&';
                   3232:         }
                   3233:         $cids=~s/\&$//;
                   3234:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3235:                           $coursehome);       
                   3236:     } else {
                   3237:         my $items = '';
                   3238:         foreach my $item (keys(%$storehash)) {
                   3239:             $items.= &escape($item).'='.
                   3240:                      &freeze_escape($$storehash{$item}).'&';
                   3241:         }
                   3242:         $items=~s/\&$//;
                   3243:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3244:                           $coursehome);
1.918     raeburn  3245:     }
                   3246:     if ($outcome eq 'unknown_cmd') {
                   3247:         my $what;
                   3248:         foreach my $cid (keys(%$storehash)) {
                   3249:             $what .= &escape($cid).'=';
1.921     raeburn  3250:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3251:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3252:             }
                   3253:             $what =~ s/\:$/&/;
                   3254:         }
                   3255:         $what =~ s/\&$//;  
                   3256:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3257:     } else {
                   3258:         return $outcome;
                   3259:     }
1.353     www      3260: }
                   3261: 
                   3262: sub courseiddump {
1.921     raeburn  3263:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3264:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3265:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3266:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3267:     my $as_hash = 1;
                   3268:     my %returnhash;
                   3269:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3270:     my %libserv = &all_library();
                   3271:     foreach my $tryserver (keys(%libserv)) {
                   3272:         if ( (  $hostidflag == 1 
                   3273: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3274: 	     || (!defined($hostidflag)) ) {
                   3275: 
1.918     raeburn  3276: 	    if (($domfilter eq '') ||
                   3277: 		(&host_domain($tryserver) eq $domfilter)) {
                   3278:                 my $rep = 
                   3279:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3280:                          $sincefilter.':'.&escape($descfilter).':'.
                   3281:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3282:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3283:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3284:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3285:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3286:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3287:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3288:                          &escape($creationcontext).':'.$domcloner,
                   3289:                          $tryserver);
1.918     raeburn  3290:                 my @pairs=split(/\&/,$rep);
                   3291:                 foreach my $item (@pairs) {
                   3292:                     my ($key,$value)=split(/\=/,$item,2);
                   3293:                     $key = &unescape($key);
                   3294:                     next if ($key =~ /^error: 2 /);
                   3295:                     my $result = &thaw_unescape($value);
                   3296:                     if (ref($result) eq 'HASH') {
                   3297:                         $returnhash{$key}=$result;
                   3298:                     } else {
1.921     raeburn  3299:                         my @responses = split(/:/,$value);
                   3300:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3301:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3302:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3303:                         }
1.1008    raeburn  3304:                     }
1.353     www      3305:                 }
                   3306:             }
                   3307:         }
                   3308:     }
                   3309:     return %returnhash;
                   3310: }
                   3311: 
1.1055    raeburn  3312: sub courselastaccess {
                   3313:     my ($cdom,$cnum,$hostidref) = @_;
                   3314:     my %returnhash;
                   3315:     if ($cdom && $cnum) {
                   3316:         my $chome = &homeserver($cnum,$cdom);
                   3317:         if ($chome ne 'no_host') {
                   3318:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3319:             &extract_lastaccess(\%returnhash,$rep);
                   3320:         }
                   3321:     } else {
                   3322:         if (!$cdom) { $cdom=''; }
                   3323:         my %libserv = &all_library();
                   3324:         foreach my $tryserver (keys(%libserv)) {
                   3325:             if (ref($hostidref) eq 'ARRAY') {
                   3326:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3327:             } 
                   3328:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3329:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3330:                 &extract_lastaccess(\%returnhash,$rep);
                   3331:             }
                   3332:         }
                   3333:     }
                   3334:     return %returnhash;
                   3335: }
                   3336: 
                   3337: sub extract_lastaccess {
                   3338:     my ($returnhash,$rep) = @_;
                   3339:     if (ref($returnhash) eq 'HASH') {
                   3340:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3341:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3342:                  $rep eq '') {
                   3343:             my @pairs=split(/\&/,$rep);
                   3344:             foreach my $item (@pairs) {
                   3345:                 my ($key,$value)=split(/\=/,$item,2);
                   3346:                 $key = &unescape($key);
                   3347:                 next if ($key =~ /^error: 2 /);
                   3348:                 $returnhash->{$key} = &thaw_unescape($value);
                   3349:             }
                   3350:         }
                   3351:     }
                   3352:     return;
                   3353: }
                   3354: 
1.658     raeburn  3355: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3356: 
                   3357: sub dcmailput {
1.685     raeburn  3358:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3359:     my $status = &Apache::lonnet::critical(
1.740     www      3360:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3361:        &escape($message),$server);
1.662     raeburn  3362:     return $status;
                   3363: }
                   3364: 
1.658     raeburn  3365: sub dcmaildump {
                   3366:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3367:     my %returnhash=();
1.846     albertel 3368: 
                   3369:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3370:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3371:                                                          &escape($enddate).':';
                   3372: 	my @esc_senders=map { &escape($_)} @$senders;
                   3373: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3374: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3375:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3376:             if (($key) && ($value)) {
                   3377:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3378:             }
                   3379:         }
                   3380:     }
                   3381:     return %returnhash;
                   3382: }
1.662     raeburn  3383: # ---------------------------------------------------------- Domain roles
                   3384: 
                   3385: sub get_domain_roles {
                   3386:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3387:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3388:         $startdate = '.';
                   3389:     }
1.1018    raeburn  3390:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3391:         $enddate = '.';
                   3392:     }
1.922     raeburn  3393:     my $rolelist;
                   3394:     if (ref($roles) eq 'ARRAY') {
                   3395:         $rolelist = join(':',@{$roles});
                   3396:     }
1.662     raeburn  3397:     my %personnel = ();
1.841     albertel 3398: 
                   3399:     my %servers = &get_servers($dom,'library');
                   3400:     foreach my $tryserver (keys(%servers)) {
                   3401: 	%{$personnel{$tryserver}}=();
                   3402: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3403: 					    &escape($startdate).':'.
                   3404: 					    &escape($enddate).':'.
                   3405: 					    &escape($rolelist), $tryserver))) {
                   3406: 	    my ($key,$value) = split(/\=/,$line,2);
                   3407: 	    if (($key) && ($value)) {
                   3408: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3409: 	    }
                   3410: 	}
1.662     raeburn  3411:     }
                   3412:     return %personnel;
                   3413: }
1.658     raeburn  3414: 
1.1057    www      3415: # ----------------------------------------------------------- Interval timing 
1.149     www      3416: 
1.504     albertel 3417: sub get_first_access {
                   3418:     my ($type,$argsymb)=@_;
1.790     albertel 3419:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3420:     if ($argsymb) { $symb=$argsymb; }
                   3421:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3422:     if ($type eq 'course') {
                   3423: 	$res='course';
                   3424:     } elsif ($type eq 'map') {
1.588     albertel 3425: 	$res=&symbread($map);
                   3426:     } else {
                   3427: 	$res=$symb;
                   3428:     }
                   3429:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3430:     return $times{"$courseid\0$res"};
1.504     albertel 3431: }
                   3432: 
                   3433: sub set_first_access {
                   3434:     my ($type)=@_;
1.790     albertel 3435:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3436:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3437:     if ($type eq 'course') {
                   3438: 	$res='course';
                   3439:     } elsif ($type eq 'map') {
1.588     albertel 3440: 	$res=&symbread($map);
                   3441:     } else {
                   3442: 	$res=$symb;
                   3443:     }
                   3444:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3445:     if (!$firstaccess) {
1.588     albertel 3446: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3447:     }
                   3448:     return 'already_set';
1.504     albertel 3449: }
                   3450: 
1.110     www      3451: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3452: 
                   3453: sub expirespread {
                   3454:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3455:     my $cid=$env{'request.course.id'}; 
1.110     www      3456:     if ($cid) {
                   3457:        my $now=time;
                   3458:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3459:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3460:                             $env{'course.'.$cid.'.num'}.
1.110     www      3461: 	        	    ':nohist_expirationdates:'.
                   3462:                             &escape($key).'='.$now,
1.620     albertel 3463:                             $env{'course.'.$cid.'.home'})
1.110     www      3464:     }
                   3465:     return 'ok';
1.14      www      3466: }
                   3467: 
1.109     www      3468: # ----------------------------------------------------- Devalidate Spreadsheets
                   3469: 
                   3470: sub devalidate {
1.325     www      3471:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3472:     my $cid=$env{'request.course.id'}; 
1.109     www      3473:     if ($cid) {
1.391     matthew  3474:         # delete the stored spreadsheets for
                   3475:         # - the student level sheet of this user in course's homespace
                   3476:         # - the assessment level sheet for this resource 
                   3477:         #   for this user in user's homespace
1.553     albertel 3478: 	# - current conditional state info
1.325     www      3479: 	my $key=$uname.':'.$udom.':';
1.109     www      3480:         my $status=
1.299     matthew  3481: 	    &del('nohist_calculatedsheets',
1.391     matthew  3482: 		 [$key.'studentcalc:'],
1.620     albertel 3483: 		 $env{'course.'.$cid.'.domain'},
                   3484: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3485: 		.' '.
                   3486: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3487: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3488:         unless ($status eq 'ok ok') {
                   3489:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3490:                     $uname.' at '.$udom.' for '.
1.109     www      3491: 		    $symb.': '.$status);
1.133     albertel 3492:         }
1.553     albertel 3493: 	&delenv('user.state.'.$cid);
1.109     www      3494:     }
                   3495: }
                   3496: 
1.265     albertel 3497: sub get_scalar {
                   3498:     my ($string,$end) = @_;
                   3499:     my $value;
                   3500:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3501: 	$value = $1;
                   3502:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3503: 	$value = $1;
                   3504:     }
                   3505:     return &unescape($value);
                   3506: }
                   3507: 
                   3508: sub array2str {
                   3509:   my (@array) = @_;
                   3510:   my $result=&arrayref2str(\@array);
                   3511:   $result=~s/^__ARRAY_REF__//;
                   3512:   $result=~s/__END_ARRAY_REF__$//;
                   3513:   return $result;
                   3514: }
                   3515: 
1.204     albertel 3516: sub arrayref2str {
                   3517:   my ($arrayref) = @_;
1.265     albertel 3518:   my $result='__ARRAY_REF__';
1.204     albertel 3519:   foreach my $elem (@$arrayref) {
1.265     albertel 3520:     if(ref($elem) eq 'ARRAY') {
                   3521:       $result.=&arrayref2str($elem).'&';
                   3522:     } elsif(ref($elem) eq 'HASH') {
                   3523:       $result.=&hashref2str($elem).'&';
                   3524:     } elsif(ref($elem)) {
                   3525:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3526:     } else {
                   3527:       $result.=&escape($elem).'&';
                   3528:     }
                   3529:   }
                   3530:   $result=~s/\&$//;
1.265     albertel 3531:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3532:   return $result;
                   3533: }
                   3534: 
1.168     albertel 3535: sub hash2str {
1.204     albertel 3536:   my (%hash) = @_;
                   3537:   my $result=&hashref2str(\%hash);
1.265     albertel 3538:   $result=~s/^__HASH_REF__//;
                   3539:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3540:   return $result;
                   3541: }
                   3542: 
                   3543: sub hashref2str {
                   3544:   my ($hashref)=@_;
1.265     albertel 3545:   my $result='__HASH_REF__';
1.800     albertel 3546:   foreach my $key (sort(keys(%$hashref))) {
                   3547:     if (ref($key) eq 'ARRAY') {
                   3548:       $result.=&arrayref2str($key).'=';
                   3549:     } elsif (ref($key) eq 'HASH') {
                   3550:       $result.=&hashref2str($key).'=';
                   3551:     } elsif (ref($key)) {
1.265     albertel 3552:       $result.='=';
1.800     albertel 3553:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3554:     } else {
1.800     albertel 3555: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3556:     }
                   3557: 
1.800     albertel 3558:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3559:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3560:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3561:       $result.=&hashref2str($hashref->{$key}).'&';
                   3562:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3563:        $result.='&';
1.800     albertel 3564:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3565:     } else {
1.800     albertel 3566:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3567:     }
                   3568:   }
1.168     albertel 3569:   $result=~s/\&$//;
1.265     albertel 3570:   $result .= '__END_HASH_REF__';
1.168     albertel 3571:   return $result;
                   3572: }
                   3573: 
                   3574: sub str2hash {
1.265     albertel 3575:     my ($string)=@_;
                   3576:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3577:     return %$hash;
                   3578: }
                   3579: 
                   3580: sub str2hashref {
1.168     albertel 3581:   my ($string) = @_;
1.265     albertel 3582: 
                   3583:   my %hash;
                   3584: 
                   3585:   if($string !~ /^__HASH_REF__/) {
                   3586:       if (! ($string eq '' || !defined($string))) {
                   3587: 	  $hash{'error'}='Not hash reference';
                   3588:       }
                   3589:       return (\%hash, $string);
                   3590:   }
                   3591: 
                   3592:   $string =~ s/^__HASH_REF__//;
                   3593: 
                   3594:   while($string !~ /^__END_HASH_REF__/) {
                   3595:       #key
                   3596:       my $key='';
                   3597:       if($string =~ /^__HASH_REF__/) {
                   3598:           ($key, $string)=&str2hashref($string);
                   3599:           if(defined($key->{'error'})) {
                   3600:               $hash{'error'}='Bad data';
                   3601:               return (\%hash, $string);
                   3602:           }
                   3603:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3604:           ($key, $string)=&str2arrayref($string);
                   3605:           if($key->[0] eq 'Array reference error') {
                   3606:               $hash{'error'}='Bad data';
                   3607:               return (\%hash, $string);
                   3608:           }
                   3609:       } else {
                   3610:           $string =~ s/^(.*?)=//;
1.267     albertel 3611: 	  $key=&unescape($1);
1.265     albertel 3612:       }
                   3613:       $string =~ s/^=//;
                   3614: 
                   3615:       #value
                   3616:       my $value='';
                   3617:       if($string =~ /^__HASH_REF__/) {
                   3618:           ($value, $string)=&str2hashref($string);
                   3619:           if(defined($value->{'error'})) {
                   3620:               $hash{'error'}='Bad data';
                   3621:               return (\%hash, $string);
                   3622:           }
                   3623:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3624:           ($value, $string)=&str2arrayref($string);
                   3625:           if($value->[0] eq 'Array reference error') {
                   3626:               $hash{'error'}='Bad data';
                   3627:               return (\%hash, $string);
                   3628:           }
                   3629:       } else {
                   3630: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3631:       }
                   3632:       $string =~ s/^&//;
                   3633: 
                   3634:       $hash{$key}=$value;
1.204     albertel 3635:   }
1.265     albertel 3636: 
                   3637:   $string =~ s/^__END_HASH_REF__//;
                   3638: 
                   3639:   return (\%hash, $string);
1.204     albertel 3640: }
                   3641: 
                   3642: sub str2array {
1.265     albertel 3643:     my ($string)=@_;
                   3644:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3645:     return @$array;
                   3646: }
                   3647: 
                   3648: sub str2arrayref {
1.204     albertel 3649:   my ($string) = @_;
1.265     albertel 3650:   my @array;
                   3651: 
                   3652:   if($string !~ /^__ARRAY_REF__/) {
                   3653:       if (! ($string eq '' || !defined($string))) {
                   3654: 	  $array[0]='Array reference error';
                   3655:       }
                   3656:       return (\@array, $string);
                   3657:   }
                   3658: 
                   3659:   $string =~ s/^__ARRAY_REF__//;
                   3660: 
                   3661:   while($string !~ /^__END_ARRAY_REF__/) {
                   3662:       my $value='';
                   3663:       if($string =~ /^__HASH_REF__/) {
                   3664:           ($value, $string)=&str2hashref($string);
                   3665:           if(defined($value->{'error'})) {
                   3666:               $array[0] ='Array reference error';
                   3667:               return (\@array, $string);
                   3668:           }
                   3669:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3670:           ($value, $string)=&str2arrayref($string);
                   3671:           if($value->[0] eq 'Array reference error') {
                   3672:               $array[0] ='Array reference error';
                   3673:               return (\@array, $string);
                   3674:           }
                   3675:       } else {
                   3676: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3677:       }
                   3678:       $string =~ s/^&//;
                   3679: 
                   3680:       push(@array, $value);
1.191     harris41 3681:   }
1.265     albertel 3682: 
                   3683:   $string =~ s/^__END_ARRAY_REF__//;
                   3684: 
                   3685:   return (\@array, $string);
1.168     albertel 3686: }
                   3687: 
1.167     albertel 3688: # -------------------------------------------------------------------Temp Store
                   3689: 
1.168     albertel 3690: sub tmpreset {
                   3691:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3692:   if (!$symb) {
                   3693:     $symb=&symbread();
1.620     albertel 3694:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3695:   }
                   3696:   $symb=escape($symb);
                   3697: 
1.620     albertel 3698:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3699:   $namespace=~s/\//\_/g;
                   3700:   $namespace=~s/\W//g;
                   3701: 
1.620     albertel 3702:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3703:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3704:   if ($domain eq 'public' && $stuname eq 'public') {
                   3705:       $stuname=$ENV{'REMOTE_ADDR'};
                   3706:   }
1.168     albertel 3707:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3708:   my %hash;
                   3709:   if (tie(%hash,'GDBM_File',
                   3710: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3711: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3712:     foreach my $key (keys(%hash)) {
1.180     albertel 3713:       if ($key=~ /:$symb/) {
1.168     albertel 3714: 	delete($hash{$key});
                   3715:       }
                   3716:     }
                   3717:   }
                   3718: }
                   3719: 
1.167     albertel 3720: sub tmpstore {
1.168     albertel 3721:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3722: 
                   3723:   if (!$symb) {
                   3724:     $symb=&symbread();
1.620     albertel 3725:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3726:   }
                   3727:   $symb=escape($symb);
                   3728: 
                   3729:   if (!$namespace) {
                   3730:     # I don't think we would ever want to store this for a course.
                   3731:     # it seems this will only be used if we don't have a course.
1.620     albertel 3732:     #$namespace=$env{'request.course.id'};
1.168     albertel 3733:     #if (!$namespace) {
1.620     albertel 3734:       $namespace=$env{'request.state'};
1.168     albertel 3735:     #}
                   3736:   }
                   3737:   $namespace=~s/\//\_/g;
                   3738:   $namespace=~s/\W//g;
1.620     albertel 3739:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3740:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3741:   if ($domain eq 'public' && $stuname eq 'public') {
                   3742:       $stuname=$ENV{'REMOTE_ADDR'};
                   3743:   }
1.168     albertel 3744:   my $now=time;
                   3745:   my %hash;
                   3746:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3747:   if (tie(%hash,'GDBM_File',
                   3748: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3749: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3750:     $hash{"version:$symb"}++;
                   3751:     my $version=$hash{"version:$symb"};
                   3752:     my $allkeys=''; 
                   3753:     foreach my $key (keys(%$storehash)) {
                   3754:       $allkeys.=$key.':';
1.591     albertel 3755:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3756:     }
                   3757:     $hash{"$version:$symb:timestamp"}=$now;
                   3758:     $allkeys.='timestamp';
                   3759:     $hash{"$version:keys:$symb"}=$allkeys;
                   3760:     if (untie(%hash)) {
                   3761:       return 'ok';
                   3762:     } else {
                   3763:       return "error:$!";
                   3764:     }
                   3765:   } else {
                   3766:     return "error:$!";
                   3767:   }
                   3768: }
1.167     albertel 3769: 
1.168     albertel 3770: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3771: 
1.168     albertel 3772: sub tmprestore {
                   3773:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3774: 
1.168     albertel 3775:   if (!$symb) {
                   3776:     $symb=&symbread();
1.620     albertel 3777:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3778:   }
                   3779:   $symb=escape($symb);
                   3780: 
1.620     albertel 3781:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3782: 
1.620     albertel 3783:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3784:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3785:   if ($domain eq 'public' && $stuname eq 'public') {
                   3786:       $stuname=$ENV{'REMOTE_ADDR'};
                   3787:   }
1.168     albertel 3788:   my %returnhash;
                   3789:   $namespace=~s/\//\_/g;
                   3790:   $namespace=~s/\W//g;
                   3791:   my %hash;
                   3792:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3793:   if (tie(%hash,'GDBM_File',
                   3794: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3795: 	  &GDBM_READER(),0640)) {
1.168     albertel 3796:     my $version=$hash{"version:$symb"};
                   3797:     $returnhash{'version'}=$version;
                   3798:     my $scope;
                   3799:     for ($scope=1;$scope<=$version;$scope++) {
                   3800:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3801:       my @keys=split(/:/,$vkeys);
                   3802:       my $key;
                   3803:       $returnhash{"$scope:keys"}=$vkeys;
                   3804:       foreach $key (@keys) {
1.591     albertel 3805: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3806: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3807:       }
                   3808:     }
1.168     albertel 3809:     if (!(untie(%hash))) {
                   3810:       return "error:$!";
                   3811:     }
                   3812:   } else {
                   3813:     return "error:$!";
                   3814:   }
                   3815:   return %returnhash;
1.167     albertel 3816: }
                   3817: 
1.9       www      3818: # ----------------------------------------------------------------------- Store
                   3819: 
                   3820: sub store {
1.124     www      3821:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3822:     my $home='';
                   3823: 
1.168     albertel 3824:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3825: 
1.213     www      3826:     $symb=&symbclean($symb);
1.122     albertel 3827:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3828: 
1.620     albertel 3829:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3830:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3831: 
                   3832:     &devalidate($symb,$stuname,$domain);
1.109     www      3833: 
                   3834:     $symb=escape($symb);
1.187     www      3835:     if (!$namespace) { 
1.620     albertel 3836:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3837:           return ''; 
                   3838:        } 
                   3839:     }
1.620     albertel 3840:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3841: 
                   3842:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3843:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3844: 
1.12      www      3845:     my $namevalue='';
1.800     albertel 3846:     foreach my $key (keys(%$storehash)) {
                   3847:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3848:     }
1.12      www      3849:     $namevalue=~s/\&$//;
1.187     www      3850:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3851:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3852: }
                   3853: 
1.47      www      3854: # -------------------------------------------------------------- Critical Store
                   3855: 
                   3856: sub cstore {
1.124     www      3857:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3858:     my $home='';
                   3859: 
1.168     albertel 3860:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3861: 
1.213     www      3862:     $symb=&symbclean($symb);
1.122     albertel 3863:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3864: 
1.620     albertel 3865:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3866:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3867: 
                   3868:     &devalidate($symb,$stuname,$domain);
1.109     www      3869: 
                   3870:     $symb=escape($symb);
1.187     www      3871:     if (!$namespace) { 
1.620     albertel 3872:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3873:           return ''; 
                   3874:        } 
                   3875:     }
1.620     albertel 3876:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3877: 
                   3878:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3879:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3880: 
1.47      www      3881:     my $namevalue='';
1.800     albertel 3882:     foreach my $key (keys(%$storehash)) {
                   3883:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3884:     }
1.47      www      3885:     $namevalue=~s/\&$//;
1.187     www      3886:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3887:     return critical
                   3888:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3889: }
                   3890: 
1.9       www      3891: # --------------------------------------------------------------------- Restore
                   3892: 
                   3893: sub restore {
1.124     www      3894:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3895:     my $home='';
                   3896: 
1.168     albertel 3897:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3898: 
1.122     albertel 3899:     if (!$symb) {
                   3900:       unless ($symb=escape(&symbread())) { return ''; }
                   3901:     } else {
1.213     www      3902:       $symb=&escape(&symbclean($symb));
1.122     albertel 3903:     }
1.188     www      3904:     if (!$namespace) { 
1.620     albertel 3905:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3906:           return ''; 
                   3907:        } 
                   3908:     }
1.620     albertel 3909:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3910:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3911:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3912:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3913: 
1.12      www      3914:     my %returnhash=();
1.800     albertel 3915:     foreach my $line (split(/\&/,$answer)) {
                   3916: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3917:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3918:     }
1.75      www      3919:     my $version;
                   3920:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3921:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3922:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3923:        }
1.75      www      3924:     }
1.13      www      3925:     return %returnhash;
1.34      www      3926: }
                   3927: 
                   3928: # ---------------------------------------------------------- Course Description
                   3929: 
                   3930: sub coursedescription {
1.731     albertel 3931:     my ($courseid,$args)=@_;
1.34      www      3932:     $courseid=~s/^\///;
1.49      www      3933:     $courseid=~s/\_/\//g;
1.34      www      3934:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3935:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3936:     my $normalid=$cdomain.'_'.$cnum;
                   3937:     # need to always cache even if we get errors otherwise we keep 
                   3938:     # trying and trying and trying to get the course description.
                   3939:     my %envhash=();
                   3940:     my %returnhash=();
1.731     albertel 3941:     
                   3942:     my $expiretime=600;
                   3943:     if ($env{'request.course.id'} eq $normalid) {
                   3944: 	$expiretime=120;
                   3945:     }
                   3946: 
                   3947:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3948:     if (!$args->{'freshen_cache'}
                   3949: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3950: 	foreach my $key (keys(%env)) {
                   3951: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3952: 	    my ($setting) = $1;
                   3953: 	    $returnhash{$setting} = $env{$key};
                   3954: 	}
                   3955: 	return %returnhash;
                   3956:     }
                   3957: 
                   3958:     # get the data agin
                   3959:     if (!$args->{'one_time'}) {
                   3960: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3961:     }
1.811     albertel 3962: 
1.34      www      3963:     if ($chome ne 'no_host') {
1.302     albertel 3964:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3965:        if (!exists($returnhash{'con_lost'})) {
                   3966:            $returnhash{'home'}= $chome;
                   3967: 	   $returnhash{'domain'} = $cdomain;
                   3968: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3969:            if (!defined($returnhash{'type'})) {
                   3970:                $returnhash{'type'} = 'Course';
                   3971:            }
1.130     albertel 3972:            while (my ($name,$value) = each %returnhash) {
1.53      www      3973:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3974:            }
1.270     www      3975:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3976:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3977: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3978:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3979:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3980:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3981:        }
                   3982:     }
1.731     albertel 3983:     if (!$args->{'one_time'}) {
1.949     raeburn  3984: 	&appenv(\%envhash);
1.731     albertel 3985:     }
1.302     albertel 3986:     return %returnhash;
1.461     www      3987: }
                   3988: 
1.1080    raeburn  3989: sub update_released_required {
                   3990:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   3991:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   3992:         $cid = $env{'request.course.id'};
                   3993:         $cdom = $env{'course.'.$cid.'.domain'};
                   3994:         $cnum = $env{'course.'.$cid.'.num'};
                   3995:         $chome = $env{'course.'.$cid.'.home'};
                   3996:     }
                   3997:     if ($needsrelease) {
                   3998:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   3999:         my $needsupdate;
                   4000:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4001:             $needsupdate = 1;
                   4002:         } else {
                   4003:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4004:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4005:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4006:                 $needsupdate = 1;
                   4007:             }
                   4008:         }
                   4009:         if ($needsupdate) {
                   4010:             my %needshash = (
                   4011:                              'internal.releaserequired' => $needsrelease,
                   4012:                             );
                   4013:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4014:             if ($putresult eq 'ok') {
                   4015:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4016:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4017:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4018:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4019:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4020:                 }
                   4021:             }
                   4022:         }
                   4023:     }
                   4024:     return;
                   4025: }
                   4026: 
1.461     www      4027: # -------------------------------------------------See if a user is privileged
                   4028: 
                   4029: sub privileged {
                   4030:     my ($username,$domain)=@_;
                   4031:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4032: 			&homeserver($username,$domain));
1.1033    raeburn  4033:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4034:         ($rolesdump =~ /^error:/)) {
                   4035:         return 0;
                   4036:     }
1.461     www      4037:     my $now=time;
                   4038:     if ($rolesdump ne '') {
1.800     albertel 4039:         foreach my $entry (split(/&/,$rolesdump)) {
                   4040: 	    if ($entry!~/^rolesdef_/) {
                   4041: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4042: 		$area=~s/\_\w\w$//;
                   4043: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4044: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4045: 		    my $active=1;
                   4046: 		    if ($tend) {
                   4047: 			if ($tend<$now) { $active=0; }
                   4048: 		    }
                   4049: 		    if ($tstart) {
                   4050: 			if ($tstart>$now) { $active=0; }
                   4051: 		    }
                   4052: 		    if ($active) { return 1; }
                   4053: 		}
                   4054: 	    }
                   4055: 	}
                   4056:     }
                   4057:     return 0;
1.9       www      4058: }
1.1       albertel 4059: 
1.103     harris41 4060: # -------------------------------------------------------- Get user privileges
1.11      www      4061: 
                   4062: sub rolesinit {
                   4063:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4064:     my $now=time;
                   4065:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4066:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4067:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4068:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4069:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4070:         return \%userroles;
                   4071:     }
1.11      www      4072:     my %allroles=();
1.678     raeburn  4073:     my %allgroups=();   
                   4074:     my $group_privs;
1.11      www      4075: 
                   4076:     if ($rolesdump ne '') {
1.800     albertel 4077:         foreach my $entry (split(/&/,$rolesdump)) {
                   4078: 	  if ($entry!~/^rolesdef_/) {
                   4079:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4080: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4081:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4082: 	    if ($role=~/^cr/) { 
1.807     albertel 4083: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4084: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4085: 		    ($tend,$tstart)=split('_',$trest);
                   4086: 		} else {
                   4087: 		    $trole=$role;
                   4088: 		}
1.678     raeburn  4089:             } elsif ($role =~ m|^gr/|) {
                   4090:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4091:                 ($trole,$group_privs) = split(/\//,$trole);
                   4092:                 $group_privs = &unescape($group_privs);
1.587     albertel 4093: 	    } else {
                   4094: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4095: 	    }
1.743     albertel 4096: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4097: 					 $username);
                   4098: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4099:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4100:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4101:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4102: 		my $spec=$trole.'.'.$area;
                   4103: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4104: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4105:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4106:                 } elsif ($trole eq 'gr') {
                   4107:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4108: 		} else {
1.567     raeburn  4109:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4110: 		}
1.12      www      4111:             }
1.662     raeburn  4112:           }
1.191     harris41 4113:         }
1.743     albertel 4114:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4115:         $userroles{'user.adv'}    = $adv;
                   4116: 	$userroles{'user.author'} = $author;
1.620     albertel 4117:         $env{'user.adv'}=$adv;
1.11      www      4118:     }
1.743     albertel 4119:     return \%userroles;  
1.11      www      4120: }
                   4121: 
1.567     raeburn  4122: sub set_arearole {
                   4123:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4124: # log the associated role with the area
                   4125:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4126:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4127: }
                   4128: 
                   4129: sub custom_roleprivs {
                   4130:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4131:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4132:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4133:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4134:         my ($rdummy,$roledef)=
                   4135:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4136:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4137:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4138:             if (defined($syspriv)) {
1.1043    raeburn  4139:                 if ($trest =~ /^$match_community$/) {
                   4140:                     $syspriv =~ s/bre\&S//; 
                   4141:                 }
1.567     raeburn  4142:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4143:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4144:             }
                   4145:             if ($tdomain ne '') {
                   4146:                 if (defined($dompriv)) {
                   4147:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4148:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4149:                 }
                   4150:                 if (($trest ne '') && (defined($coursepriv))) {
                   4151:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4152:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4153:                 }
                   4154:             }
                   4155:         }
                   4156:     }
                   4157: }
                   4158: 
1.678     raeburn  4159: sub group_roleprivs {
                   4160:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4161:     my $access = 1;
                   4162:     my $now = time;
                   4163:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4164:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4165:     if ($access) {
1.811     albertel 4166:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4167:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4168:     }
                   4169: }
1.567     raeburn  4170: 
                   4171: sub standard_roleprivs {
                   4172:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4173:     if (defined($pr{$trole.':s'})) {
                   4174:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4175:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4176:     }
                   4177:     if ($tdomain ne '') {
                   4178:         if (defined($pr{$trole.':d'})) {
                   4179:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4180:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4181:         }
                   4182:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4183:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4184:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4185:         }
                   4186:     }
                   4187: }
                   4188: 
                   4189: sub set_userprivs {
1.1064    raeburn  4190:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4191:     my $author=0;
                   4192:     my $adv=0;
1.678     raeburn  4193:     my %grouproles = ();
                   4194:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4195:         my @groupkeys; 
1.1000    raeburn  4196:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4197:             push(@groupkeys,$role);
                   4198:         }
                   4199:         if (ref($groups_roles) eq 'HASH') {
                   4200:             foreach my $key (keys(%{$groups_roles})) {
                   4201:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4202:                     push(@groupkeys,$key);
                   4203:                 }
                   4204:             }
                   4205:         }
                   4206:         if (@groupkeys > 0) {
                   4207:             foreach my $role (@groupkeys) {
                   4208:                 my ($trole,$area,$sec,$extendedarea);
                   4209:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4210:                     $trole = $1;
                   4211:                     $area = $2;
                   4212:                     $sec = $3;
                   4213:                     $extendedarea = $area.$sec;
                   4214:                     if (exists($$allgroups{$area})) {
                   4215:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4216:                             my $spec = $trole.'.'.$extendedarea;
                   4217:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4218:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4219:                         }
1.678     raeburn  4220:                     }
                   4221:                 }
                   4222:             }
                   4223:         }
                   4224:     }
1.800     albertel 4225:     foreach my $group (keys(%grouproles)) {
                   4226:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4227:     }
1.800     albertel 4228:     foreach my $role (keys(%{$allroles})) {
                   4229:         my %thesepriv;
1.941     raeburn  4230:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4231:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4232:             if ($item ne '') {
                   4233:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4234:                 if ($restrictions eq '') {
                   4235:                     $thesepriv{$privilege}='F';
                   4236:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4237:                     $thesepriv{$privilege}.=$restrictions;
                   4238:                 }
                   4239:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4240:             }
                   4241:         }
                   4242:         my $thesestr='';
1.800     albertel 4243:         foreach my $priv (keys(%thesepriv)) {
                   4244: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4245: 	}
                   4246:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4247:     }
                   4248:     return ($author,$adv);
                   4249: }
                   4250: 
1.994     raeburn  4251: sub role_status {
1.1002    raeburn  4252:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4253:     my @pwhere = ();
                   4254:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4255:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4256:         unless (!defined($$role) || $$role eq '') {
                   4257:             $$where=join('.',@pwhere);
                   4258:             $$trolecode=$$role.'.'.$$where;
                   4259:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4260:             $$tstatus='is';
                   4261:             if ($$tstart && $$tstart>$then) {
                   4262:                 $$tstatus='future';
1.1034    raeburn  4263:                 if ($$tstart<$now) {
                   4264:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4265:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4266:                             my (%allroles,%allgroups,$group_privs,
                   4267:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4268:                             my %userroles = (
                   4269:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4270:                             );
1.1064    raeburn  4271:                             @rolecodes = ('cm'); 
1.1002    raeburn  4272:                             my $spec=$$role.'.'.$$where;
                   4273:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4274:                             if ($$role =~ /^cr\//) {
                   4275:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4276:                                 push(@rolecodes,'cr');
1.1002    raeburn  4277:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4278:                                 push(@rolecodes,$$role);
1.1002    raeburn  4279:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4280:                                                     $env{'user.name'});
1.1064    raeburn  4281:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4282:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4283:                                 $group_privs = &unescape($group_privs);
                   4284:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4285:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4286:                                 if (keys(%course_roles) > 0) {
                   4287:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4288:                                     if ($tdomain ne '' && $tnum ne '') { 
                   4289:                                         foreach my $key (keys(%course_roles)) {
                   4290:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4291:                                                 my $crsrole = $1;
                   4292:                                                 my $crssec = $2;
                   4293:                                                 if ($crsrole =~ /^cr/) {
                   4294:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4295:                                                         push(@rolecodes,'cr');
                   4296:                                                     }
                   4297:                                                 } else {
                   4298:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4299:                                                         push(@rolecodes,$crsrole);
                   4300:                                                     }
                   4301:                                                 }
                   4302:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4303:                                                 if ($crssec ne '') {
                   4304:                                                     $rolekey .= '/'.$crssec;
                   4305:                                                 }
                   4306:                                                 $rolekey .= './';
                   4307:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4308:                                             }
                   4309:                                         }
                   4310:                                     }
                   4311:                                 }
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) {
                   4325:                 if ($$tend<$then) {
                   4326:                     $$tstatus='expired';
                   4327:                 } elsif ($$tend<$now) {
                   4328:                     $$tstatus='will_not';
                   4329:                 }
                   4330:             }
                   4331:         }
                   4332:     }
                   4333: }
                   4334: 
                   4335: sub check_adhoc_privs {
1.1088    raeburn  4336:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4337:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4338:     if ($env{$cckey}) {
                   4339:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4340:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4341:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4342:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4343:         }
                   4344:     } else {
1.1088    raeburn  4345:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4346:     }
                   4347: }
                   4348: 
                   4349: sub set_adhoc_privileges {
                   4350: # role can be cc or ca
1.1088    raeburn  4351:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4352:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4353:     my $spec = $role.'.'.$area;
                   4354:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4355:                                   $env{'user.name'});
                   4356:     my %ccrole = ();
                   4357:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4358:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4359:     &appenv(\%userroles,[$role,'cm']);
                   4360:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4361:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4362:         &appenv( {'request.role'        => $spec,
                   4363:                   'request.role.domain' => $dcdom,
                   4364:                   'request.course.sec'  => ''
                   4365:                  }
                   4366:                );
                   4367:         my $tadv=0;
                   4368:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4369:         &appenv({'request.role.adv'    => $tadv});
                   4370:     }
1.994     raeburn  4371: }
                   4372: 
1.12      www      4373: # --------------------------------------------------------------- get interface
                   4374: 
                   4375: sub get {
1.131     albertel 4376:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4377:    my $items='';
1.800     albertel 4378:    foreach my $item (@$storearr) {
                   4379:        $items.=&escape($item).'&';
1.191     harris41 4380:    }
1.12      www      4381:    $items=~s/\&$//;
1.620     albertel 4382:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4383:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4384:    my $uhome=&homeserver($uname,$udomain);
                   4385: 
1.133     albertel 4386:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4387:    my @pairs=split(/\&/,$rep);
1.273     albertel 4388:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4389:      return @pairs;
                   4390:    }
1.15      www      4391:    my %returnhash=();
1.42      www      4392:    my $i=0;
1.800     albertel 4393:    foreach my $item (@$storearr) {
                   4394:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4395:       $i++;
1.191     harris41 4396:    }
1.15      www      4397:    return %returnhash;
1.27      www      4398: }
                   4399: 
                   4400: # --------------------------------------------------------------- del interface
                   4401: 
                   4402: sub del {
1.133     albertel 4403:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4404:    my $items='';
1.800     albertel 4405:    foreach my $item (@$storearr) {
                   4406:        $items.=&escape($item).'&';
1.191     harris41 4407:    }
1.984     neumanie 4408: 
1.27      www      4409:    $items=~s/\&$//;
1.620     albertel 4410:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4411:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4412:    my $uhome=&homeserver($uname,$udomain);
                   4413:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4414: }
                   4415: 
                   4416: # -------------------------------------------------------------- dump interface
                   4417: 
                   4418: sub dump {
1.1086    raeburn  4419:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4420:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4421:     if (!$uname) { $uname=$env{'user.name'}; }
                   4422:     my $uhome=&homeserver($uname,$udomain);
                   4423:     if ($regexp) {
                   4424: 	$regexp=&escape($regexp);
                   4425:     } else {
                   4426: 	$regexp='.';
                   4427:     }
1.1086    raeburn  4428:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4429:     my @pairs=split(/\&/,$rep);
                   4430:     my %returnhash=();
                   4431:     foreach my $item (@pairs) {
                   4432: 	my ($key,$value)=split(/=/,$item,2);
                   4433: 	$key = &unescape($key);
                   4434: 	next if ($key =~ /^error: 2 /);
                   4435: 	$returnhash{$key}=&thaw_unescape($value);
                   4436:     }
                   4437:     return %returnhash;
1.407     www      4438: }
                   4439: 
1.717     albertel 4440: # --------------------------------------------------------- dumpstore interface
                   4441: 
                   4442: sub dumpstore {
                   4443:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4444:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4445:    if (!$uname) { $uname=$env{'user.name'}; }
                   4446:    my $uhome=&homeserver($uname,$udomain);
                   4447:    if ($regexp) {
                   4448:        $regexp=&escape($regexp);
                   4449:    } else {
                   4450:        $regexp='.';
                   4451:    }
                   4452:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4453:    my @pairs=split(/\&/,$rep);
                   4454:    my %returnhash=();
                   4455:    foreach my $item (@pairs) {
                   4456:        my ($key,$value)=split(/=/,$item,2);
                   4457:        next if ($key =~ /^error: 2 /);
                   4458:        $returnhash{$key}=&thaw_unescape($value);
                   4459:    }
                   4460:    return %returnhash;
1.717     albertel 4461: }
                   4462: 
1.407     www      4463: # -------------------------------------------------------------- keys interface
                   4464: 
                   4465: sub getkeys {
                   4466:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4467:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4468:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4469:    my $uhome=&homeserver($uname,$udomain);
                   4470:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4471:    my @keyarray=();
1.800     albertel 4472:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4473:       next if ($key =~ /^error: 2 /);
1.800     albertel 4474:       push(@keyarray,&unescape($key));
1.407     www      4475:    }
                   4476:    return @keyarray;
1.318     matthew  4477: }
                   4478: 
1.319     matthew  4479: # --------------------------------------------------------------- currentdump
                   4480: sub currentdump {
1.328     matthew  4481:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4482:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4483:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4484:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4485:    my $uhome = &homeserver($sname,$sdom);
                   4486:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4487:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4488:    #
1.318     matthew  4489:    my %returnhash=();
1.319     matthew  4490:    #
                   4491:    if ($rep eq "unknown_cmd") { 
                   4492:        # an old lond will not know currentdump
                   4493:        # Do a dump and make it look like a currentdump
1.822     albertel 4494:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4495:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4496:        my %hash = @tmp;
                   4497:        @tmp=();
1.424     matthew  4498:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4499:    } else {
                   4500:        my @pairs=split(/\&/,$rep);
1.800     albertel 4501:        foreach my $pair (@pairs) {
                   4502:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4503:            my ($symb,$param) = split(/:/,$key);
                   4504:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4505:                                                         &thaw_unescape($value);
1.319     matthew  4506:        }
1.191     harris41 4507:    }
1.12      www      4508:    return %returnhash;
1.424     matthew  4509: }
                   4510: 
                   4511: sub convert_dump_to_currentdump{
                   4512:     my %hash = %{shift()};
                   4513:     my %returnhash;
                   4514:     # Code ripped from lond, essentially.  The only difference
                   4515:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4516:     # we might run in to problems with parameter names =~ /^v\./
                   4517:     while (my ($key,$value) = each(%hash)) {
                   4518:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4519: 	$symb  = &unescape($symb);
                   4520: 	$param = &unescape($param);
1.424     matthew  4521:         next if ($v eq 'version' || $symb eq 'keys');
                   4522:         next if (exists($returnhash{$symb}) &&
                   4523:                  exists($returnhash{$symb}->{$param}) &&
                   4524:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4525:         $returnhash{$symb}->{$param}=$value;
                   4526:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4527:     }
                   4528:     #
                   4529:     # Remove all of the keys in the hashes which keep track of
                   4530:     # the version of the parameter.
                   4531:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4532:         # use a foreach because we are going to delete from the hash.
                   4533:         foreach my $key (keys(%$param_hash)) {
                   4534:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4535:         }
                   4536:     }
                   4537:     return \%returnhash;
1.12      www      4538: }
                   4539: 
1.627     albertel 4540: # ------------------------------------------------------ critical inc interface
                   4541: 
                   4542: sub cinc {
                   4543:     return &inc(@_,'critical');
                   4544: }
                   4545: 
1.449     matthew  4546: # --------------------------------------------------------------- inc interface
                   4547: 
                   4548: sub inc {
1.627     albertel 4549:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4550:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4551:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4552:     my $uhome=&homeserver($uname,$udomain);
                   4553:     my $items='';
                   4554:     if (! ref($store)) {
                   4555:         # got a single value, so use that instead
                   4556:         $items = &escape($store).'=&';
                   4557:     } elsif (ref($store) eq 'SCALAR') {
                   4558:         $items = &escape($$store).'=&';        
                   4559:     } elsif (ref($store) eq 'ARRAY') {
                   4560:         $items = join('=&',map {&escape($_);} @{$store});
                   4561:     } elsif (ref($store) eq 'HASH') {
                   4562:         while (my($key,$value) = each(%{$store})) {
                   4563:             $items.= &escape($key).'='.&escape($value).'&';
                   4564:         }
                   4565:     }
                   4566:     $items=~s/\&$//;
1.627     albertel 4567:     if ($critical) {
                   4568: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4569:     } else {
                   4570: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4571:     }
1.449     matthew  4572: }
                   4573: 
1.12      www      4574: # --------------------------------------------------------------- put interface
                   4575: 
                   4576: sub put {
1.134     albertel 4577:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4579:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4580:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4581:    my $items='';
1.800     albertel 4582:    foreach my $item (keys(%$storehash)) {
                   4583:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4584:    }
1.12      www      4585:    $items=~s/\&$//;
1.134     albertel 4586:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4587: }
                   4588: 
1.631     albertel 4589: # ------------------------------------------------------------ newput interface
                   4590: 
                   4591: sub newput {
                   4592:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4593:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4594:    if (!$uname) { $uname=$env{'user.name'}; }
                   4595:    my $uhome=&homeserver($uname,$udomain);
                   4596:    my $items='';
                   4597:    foreach my $key (keys(%$storehash)) {
                   4598:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4599:    }
                   4600:    $items=~s/\&$//;
                   4601:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4602: }
                   4603: 
                   4604: # ---------------------------------------------------------  putstore interface
                   4605: 
1.524     raeburn  4606: sub putstore {
1.715     albertel 4607:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4608:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4609:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4610:    my $uhome=&homeserver($uname,$udomain);
                   4611:    my $items='';
1.715     albertel 4612:    foreach my $key (keys(%$storehash)) {
                   4613:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4614:    }
1.715     albertel 4615:    $items=~s/\&$//;
1.716     albertel 4616:    my $esc_symb=&escape($symb);
                   4617:    my $esc_v=&escape($version);
1.715     albertel 4618:    my $reply =
1.716     albertel 4619:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4620: 	      $uhome);
                   4621:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4622:        # gfall back to way things use to be done
1.715     albertel 4623:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4624: 			    $uname);
1.524     raeburn  4625:    }
1.715     albertel 4626:    return $reply;
                   4627: }
                   4628: 
                   4629: sub old_putstore {
1.716     albertel 4630:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4631:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4632:     if (!$uname) { $uname=$env{'user.name'}; }
                   4633:     my $uhome=&homeserver($uname,$udomain);
                   4634:     my %newstorehash;
1.800     albertel 4635:     foreach my $item (keys(%$storehash)) {
                   4636: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4637: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4638:     }
                   4639:     my $items='';
                   4640:     my %allitems = ();
1.800     albertel 4641:     foreach my $item (keys(%newstorehash)) {
                   4642: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4643: 	    my $key = $1.':keys:'.$2;
                   4644: 	    $allitems{$key} .= $3.':';
                   4645: 	}
1.800     albertel 4646: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4647:     }
1.800     albertel 4648:     foreach my $item (keys(%allitems)) {
                   4649: 	$allitems{$item} =~ s/\:$//;
                   4650: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4651:     }
                   4652:     $items=~s/\&$//;
                   4653:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4654: }
                   4655: 
1.47      www      4656: # ------------------------------------------------------ critical put interface
                   4657: 
                   4658: sub cput {
1.134     albertel 4659:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4660:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4661:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4662:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4663:    my $items='';
1.800     albertel 4664:    foreach my $item (keys(%$storehash)) {
                   4665:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4666:    }
1.47      www      4667:    $items=~s/\&$//;
1.134     albertel 4668:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4669: }
                   4670: 
                   4671: # -------------------------------------------------------------- eget interface
                   4672: 
                   4673: sub eget {
1.133     albertel 4674:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4675:    my $items='';
1.800     albertel 4676:    foreach my $item (@$storearr) {
                   4677:        $items.=&escape($item).'&';
1.191     harris41 4678:    }
1.12      www      4679:    $items=~s/\&$//;
1.620     albertel 4680:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4681:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4682:    my $uhome=&homeserver($uname,$udomain);
                   4683:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4684:    my @pairs=split(/\&/,$rep);
                   4685:    my %returnhash=();
1.42      www      4686:    my $i=0;
1.800     albertel 4687:    foreach my $item (@$storearr) {
                   4688:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4689:       $i++;
1.191     harris41 4690:    }
1.12      www      4691:    return %returnhash;
                   4692: }
                   4693: 
1.667     albertel 4694: # ------------------------------------------------------------ tmpput interface
                   4695: sub tmpput {
1.802     raeburn  4696:     my ($storehash,$server,$context)=@_;
1.667     albertel 4697:     my $items='';
1.800     albertel 4698:     foreach my $item (keys(%$storehash)) {
                   4699: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4700:     }
                   4701:     $items=~s/\&$//;
1.802     raeburn  4702:     if (defined($context)) {
                   4703:         $items .= ':'.&escape($context);
                   4704:     }
1.667     albertel 4705:     return &reply("tmpput:$items",$server);
                   4706: }
                   4707: 
                   4708: # ------------------------------------------------------------ tmpget interface
                   4709: sub tmpget {
1.688     albertel 4710:     my ($token,$server)=@_;
                   4711:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4712:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4713:     my %returnhash;
                   4714:     foreach my $item (split(/\&/,$rep)) {
                   4715: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4716:         next if ($key =~ /^error: 2 /);
1.667     albertel 4717: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4718:     }
                   4719:     return %returnhash;
                   4720: }
                   4721: 
1.688     albertel 4722: # ------------------------------------------------------------ tmpget interface
                   4723: sub tmpdel {
                   4724:     my ($token,$server)=@_;
                   4725:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4726:     return &reply("tmpdel:$token",$server);
                   4727: }
                   4728: 
1.765     albertel 4729: # -------------------------------------------------- portfolio access checking
                   4730: 
                   4731: sub portfolio_access {
1.766     albertel 4732:     my ($requrl) = @_;
1.765     albertel 4733:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4734:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4735:     if ($result) {
                   4736:         my %setters;
                   4737:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4738:             my ($startblock,$endblock) =
                   4739:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4740:             if ($startblock && $endblock) {
                   4741:                 return 'B';
                   4742:             }
                   4743:         } else {
                   4744:             my ($startblock,$endblock) =
                   4745:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4746:             if ($startblock && $endblock) {
                   4747:                 return 'B';
                   4748:             }
                   4749:         }
                   4750:     }
1.765     albertel 4751:     if ($result eq 'ok') {
1.766     albertel 4752:        return 'F';
1.765     albertel 4753:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4754:        return 'A';
1.765     albertel 4755:     }
1.766     albertel 4756:     return '';
1.765     albertel 4757: }
                   4758: 
                   4759: sub get_portfolio_access {
1.767     albertel 4760:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4761: 
                   4762:     if (!ref($access_hash)) {
                   4763: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4764: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4765: 						   $file_name);
                   4766: 	$access_hash = $access_controls{$file_name};
                   4767:     }
                   4768: 
1.765     albertel 4769:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4770:     my $now = time;
                   4771:     if (ref($access_hash) eq 'HASH') {
                   4772:         foreach my $key (keys(%{$access_hash})) {
                   4773:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4774:             if ($start > $now) {
                   4775:                 next;
                   4776:             }
                   4777:             if ($end && $end<$now) {
                   4778:                 next;
                   4779:             }
                   4780:             if ($scope eq 'public') {
                   4781:                 $public = $key;
                   4782:                 last;
                   4783:             } elsif ($scope eq 'guest') {
                   4784:                 $guest = $key;
                   4785:             } elsif ($scope eq 'domains') {
                   4786:                 push(@domains,$key);
                   4787:             } elsif ($scope eq 'users') {
                   4788:                 push(@users,$key);
                   4789:             } elsif ($scope eq 'course') {
                   4790:                 push(@courses,$key);
                   4791:             } elsif ($scope eq 'group') {
                   4792:                 push(@groups,$key);
                   4793:             }
                   4794:         }
                   4795:         if ($public) {
                   4796:             return 'ok';
                   4797:         }
                   4798:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4799:             if ($guest) {
                   4800:                 return $guest;
                   4801:             }
                   4802:         } else {
                   4803:             if (@domains > 0) {
                   4804:                 foreach my $domkey (@domains) {
                   4805:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4806:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4807:                             return 'ok';
                   4808:                         }
                   4809:                     }
                   4810:                 }
                   4811:             }
                   4812:             if (@users > 0) {
                   4813:                 foreach my $userkey (@users) {
1.865     raeburn  4814:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4815:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4816:                             if (ref($item) eq 'HASH') {
                   4817:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4818:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4819:                                     return 'ok';
                   4820:                                 }
                   4821:                             }
                   4822:                         }
                   4823:                     } 
1.765     albertel 4824:                 }
                   4825:             }
                   4826:             my %roleshash;
                   4827:             my @courses_and_groups = @courses;
                   4828:             push(@courses_and_groups,@groups); 
                   4829:             if (@courses_and_groups > 0) {
                   4830:                 my (%allgroups,%allroles); 
                   4831:                 my ($start,$end,$role,$sec,$group);
                   4832:                 foreach my $envkey (%env) {
1.1060    raeburn  4833:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4834:                         my $cid = $2.'_'.$3; 
                   4835:                         if ($1 eq 'gr') {
                   4836:                             $group = $4;
                   4837:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4838:                         } else {
                   4839:                             if ($4 eq '') {
                   4840:                                 $sec = 'none';
                   4841:                             } else {
                   4842:                                 $sec = $4;
                   4843:                             }
                   4844:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4845:                         }
1.811     albertel 4846:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4847:                         my $cid = $2.'_'.$3;
                   4848:                         if ($4 eq '') {
                   4849:                             $sec = 'none';
                   4850:                         } else {
                   4851:                             $sec = $4;
                   4852:                         }
                   4853:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4854:                     }
                   4855:                 }
                   4856:                 if (keys(%allroles) == 0) {
                   4857:                     return;
                   4858:                 }
                   4859:                 foreach my $key (@courses_and_groups) {
                   4860:                     my %content = %{$$access_hash{$key}};
                   4861:                     my $cnum = $content{'number'};
                   4862:                     my $cdom = $content{'domain'};
                   4863:                     my $cid = $cdom.'_'.$cnum;
                   4864:                     if (!exists($allroles{$cid})) {
                   4865:                         next;
                   4866:                     }    
                   4867:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4868:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4869:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4870:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4871:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4872:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4873:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4874:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4875:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4876:                                         if (grep/^all$/,@sections) {
                   4877:                                             return 'ok';
                   4878:                                         } else {
                   4879:                                             if (grep/^$sec$/,@sections) {
                   4880:                                                 return 'ok';
                   4881:                                             }
                   4882:                                         }
                   4883:                                     }
                   4884:                                 }
                   4885:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4886:                                     if (grep/^none$/,@groups) {
                   4887:                                         return 'ok';
                   4888:                                     }
                   4889:                                 } else {
                   4890:                                     if (grep/^all$/,@groups) {
                   4891:                                         return 'ok';
                   4892:                                     } 
                   4893:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4894:                                         if (grep/^$group$/,@groups) {
                   4895:                                             return 'ok';
                   4896:                                         }
                   4897:                                     }
                   4898:                                 } 
                   4899:                             }
                   4900:                         }
                   4901:                     }
                   4902:                 }
                   4903:             }
                   4904:             if ($guest) {
                   4905:                 return $guest;
                   4906:             }
                   4907:         }
                   4908:     }
                   4909:     return;
                   4910: }
                   4911: 
                   4912: sub course_group_datechecker {
                   4913:     my ($dates,$now,$status) = @_;
                   4914:     my ($start,$end) = split(/\./,$dates);
                   4915:     if (!$start && !$end) {
                   4916:         return 'ok';
                   4917:     }
                   4918:     if (grep/^active$/,@{$status}) {
                   4919:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4920:             return 'ok';
                   4921:         }
                   4922:     }
                   4923:     if (grep/^previous$/,@{$status}) {
                   4924:         if ($end > $now ) {
                   4925:             return 'ok';
                   4926:         }
                   4927:     }
                   4928:     if (grep/^future$/,@{$status}) {
                   4929:         if ($start > $now) {
                   4930:             return 'ok';
                   4931:         }
                   4932:     }
                   4933:     return; 
                   4934: }
                   4935: 
                   4936: sub parse_portfolio_url {
                   4937:     my ($url) = @_;
                   4938: 
                   4939:     my ($type,$udom,$unum,$group,$file_name);
                   4940:     
1.823     albertel 4941:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4942: 	$type = 1;
                   4943:         $udom = $1;
                   4944:         $unum = $2;
                   4945:         $file_name = $3;
1.823     albertel 4946:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4947: 	$type = 2;
                   4948:         $udom = $1;
                   4949:         $unum = $2;
                   4950:         $group = $3;
                   4951:         $file_name = $3.'/'.$4;
                   4952:     }
                   4953:     if (wantarray) {
                   4954: 	return ($type,$udom,$unum,$file_name,$group);
                   4955:     }
                   4956:     return $type;
                   4957: }
                   4958: 
                   4959: sub is_portfolio_url {
                   4960:     my ($url) = @_;
                   4961:     return scalar(&parse_portfolio_url($url));
                   4962: }
                   4963: 
1.798     raeburn  4964: sub is_portfolio_file {
                   4965:     my ($file) = @_;
1.820     raeburn  4966:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4967:         return 1;
                   4968:     }
                   4969:     return;
                   4970: }
                   4971: 
1.976     raeburn  4972: sub usertools_access {
1.1084    raeburn  4973:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  4974:     my ($access,%tools);
                   4975:     if ($context eq '') {
                   4976:         $context = 'tools';
                   4977:     }
                   4978:     if ($context eq 'requestcourses') {
                   4979:         %tools = (
                   4980:                       official   => 1,
                   4981:                       unofficial => 1,
1.1006    raeburn  4982:                       community  => 1,
1.985     raeburn  4983:                  );
                   4984:     } else {
                   4985:         %tools = (
                   4986:                       aboutme   => 1,
                   4987:                       blog      => 1,
                   4988:                       portfolio => 1,
                   4989:                  );
                   4990:     }
1.976     raeburn  4991:     return if (!defined($tools{$tool}));
                   4992: 
                   4993:     if ((!defined($udom)) || (!defined($uname))) {
                   4994:         $udom = $env{'user.domain'};
                   4995:         $uname = $env{'user.name'};
                   4996:     }
                   4997: 
1.978     raeburn  4998:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4999:         if ($action ne 'reload') {
1.985     raeburn  5000:             if ($context eq 'requestcourses') {
                   5001:                 return $env{'environment.canrequest.'.$tool};
                   5002:             } else {
                   5003:                 return $env{'environment.availabletools.'.$tool};
                   5004:             }
                   5005:         }
1.976     raeburn  5006:     }
                   5007: 
                   5008:     my ($toolstatus,$inststatus);
                   5009: 
1.985     raeburn  5010:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5011:          ($action ne 'reload')) {
                   5012:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5013:         $inststatus = $env{'environment.inststatus'};
                   5014:     } else {
1.1084    raeburn  5015:         if (ref($userenvref) eq 'HASH') {
                   5016:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5017:             $inststatus = $userenvref->{'inststatus'};
                   5018:         } else {
                   5019:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5020:             $toolstatus = $userenv{$context.'.'.$tool};
                   5021:             $inststatus = $userenv{'inststatus'};
                   5022:         }
1.976     raeburn  5023:     }
                   5024: 
                   5025:     if ($toolstatus ne '') {
                   5026:         if ($toolstatus) {
                   5027:             $access = 1;
                   5028:         } else {
                   5029:             $access = 0;
                   5030:         }
                   5031:         return $access;
                   5032:     }
                   5033: 
1.1084    raeburn  5034:     my ($is_adv,%domdef);
                   5035:     if (ref($is_advref) eq 'HASH') {
                   5036:         $is_adv = $is_advref->{'is_adv'};
                   5037:     } else {
                   5038:         $is_adv = &is_advanced_user($udom,$uname);
                   5039:     }
                   5040:     if (ref($domdefref) eq 'HASH') {
                   5041:         %domdef = %{$domdefref};
                   5042:     } else {
                   5043:         %domdef = &get_domain_defaults($udom);
                   5044:     }
1.976     raeburn  5045:     if (ref($domdef{$tool}) eq 'HASH') {
                   5046:         if ($is_adv) {
                   5047:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5048:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5049:                     $access = 1;
                   5050:                 } else {
                   5051:                     $access = 0;
                   5052:                 }
                   5053:                 return $access;
                   5054:             }
                   5055:         }
                   5056:         if ($inststatus ne '') {
                   5057:             my ($hasaccess,$hasnoaccess);
                   5058:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5059:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5060:                     if ($domdef{$tool}{$affiliation}) {
                   5061:                         $hasaccess = 1;
                   5062:                     } else {
                   5063:                         $hasnoaccess = 1;
                   5064:                     }
                   5065:                 }
                   5066:             }
                   5067:             if ($hasaccess || $hasnoaccess) {
                   5068:                 if ($hasaccess) {
                   5069:                     $access = 1;
                   5070:                 } elsif ($hasnoaccess) {
                   5071:                     $access = 0; 
                   5072:                 }
                   5073:                 return $access;
                   5074:             }
                   5075:         } else {
                   5076:             if ($domdef{$tool}{'default'} ne '') {
                   5077:                 if ($domdef{$tool}{'default'}) {
                   5078:                     $access = 1;
                   5079:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5080:                     $access = 0;
                   5081:                 }
                   5082:                 return $access;
                   5083:             }
                   5084:         }
                   5085:     } else {
1.985     raeburn  5086:         if ($context eq 'tools') {
                   5087:             $access = 1;
                   5088:         } else {
                   5089:             $access = 0;
                   5090:         }
1.976     raeburn  5091:         return $access;
                   5092:     }
                   5093: }
                   5094: 
1.1050    raeburn  5095: sub is_course_owner {
                   5096:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5097:     if (($udom eq '') || ($uname eq '')) {
                   5098:         $udom = $env{'user.domain'};
                   5099:         $uname = $env{'user.name'};
                   5100:     }
                   5101:     unless (($udom eq '') || ($uname eq '')) {
                   5102:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5103:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5104:                 return 1;
                   5105:             } else {
                   5106:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5107:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5108:                     return 1;
                   5109:                 }
                   5110:             }
                   5111:         }
                   5112:     }
                   5113:     return;
                   5114: }
                   5115: 
1.976     raeburn  5116: sub is_advanced_user {
                   5117:     my ($udom,$uname) = @_;
1.1085    raeburn  5118:     if ($udom ne '' && $uname ne '') {
                   5119:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5120:             return $env{'user.adv'};  
                   5121:         }
                   5122:     }
1.976     raeburn  5123:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5124:     my %allroles;
                   5125:     my $is_adv;
                   5126:     foreach my $role (keys(%roleshash)) {
                   5127:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5128:         my $area = '/'.$tdomain.'/'.$trest;
                   5129:         if ($sec ne '') {
                   5130:             $area .= '/'.$sec;
                   5131:         }
                   5132:         if (($area ne '') && ($trole ne '')) {
                   5133:             my $spec=$trole.'.'.$area;
                   5134:             if ($trole =~ /^cr\//) {
                   5135:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5136:             } elsif ($trole ne 'gr') {
                   5137:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5138:             }
                   5139:         }
                   5140:     }
                   5141:     foreach my $role (keys(%allroles)) {
                   5142:         last if ($is_adv);
                   5143:         foreach my $item (split(/:/,$allroles{$role})) {
                   5144:             if ($item ne '') {
                   5145:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5146:                 if ($privilege eq 'adv') {
                   5147:                     $is_adv = 1;
                   5148:                     last;
                   5149:                 }
                   5150:             }
                   5151:         }
                   5152:     }
                   5153:     return $is_adv;
                   5154: }
1.798     raeburn  5155: 
1.1035    raeburn  5156: sub check_can_request {
1.1036    raeburn  5157:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5158:     my $canreq = 0;
                   5159:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5160:     my @options = ('approval','validate','autolimit');
                   5161:     my $optregex = join('|',@options);
                   5162:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5163:         foreach my $type (@{$types}) {
                   5164:             if (&usertools_access($env{'user.name'},
                   5165:                                   $env{'user.domain'},
                   5166:                                   $type,undef,'requestcourses')) {
                   5167:                 $canreq ++;
1.1036    raeburn  5168:                 if (ref($request_domains) eq 'HASH') {
                   5169:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5170:                 }
1.1035    raeburn  5171:                 if ($dom eq $env{'user.domain'}) {
                   5172:                     $can_request->{$type} = 1;
                   5173:                 }
                   5174:             }
                   5175:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5176:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5177:                 if (@curr > 0) {
1.1036    raeburn  5178:                     foreach my $item (@curr) {
                   5179:                         if (ref($request_domains) eq 'HASH') {
                   5180:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5181:                             if ($otherdom ne '') {
                   5182:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5183:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5184:                                         push(@{$request_domains->{$type}},$otherdom);
                   5185:                                     }
                   5186:                                 } else {
                   5187:                                     push(@{$request_domains->{$type}},$otherdom);
                   5188:                                 }
                   5189:                             }
                   5190:                         }
                   5191:                     }
                   5192:                     unless($dom eq $env{'user.domain'}) {
                   5193:                         $canreq ++;
1.1035    raeburn  5194:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5195:                             $can_request->{$type} = 1;
                   5196:                         }
                   5197:                     }
                   5198:                 }
                   5199:             }
                   5200:         }
                   5201:     }
                   5202:     return $canreq;
                   5203: }
                   5204: 
1.341     www      5205: # ---------------------------------------------- Custom access rule evaluation
                   5206: 
                   5207: sub customaccess {
                   5208:     my ($priv,$uri)=@_;
1.807     albertel 5209:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5210:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5211:     $udom = &LONCAPA::clean_domain($udom);
                   5212:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5213:     my $access=0;
1.800     albertel 5214:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5215: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5216: 	if ($type eq 'user') {
                   5217: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5218: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5219: 		if ($tdom) {
                   5220: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5221: 		}
1.896     albertel 5222: 		if ($tuname) {
                   5223: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5224: 		}
                   5225: 		$access=($effect eq 'allow');
                   5226: 		last;
                   5227: 	    }
                   5228: 	} else {
                   5229: 	    if ($role) {
                   5230: 		if ($role ne $urole) { next; }
                   5231: 	    }
                   5232: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5233: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5234: 		if ($tdom) {
                   5235: 		    if ($tdom ne $udom) { next; }
                   5236: 		}
                   5237: 		if ($tcrs) {
                   5238: 		    if ($tcrs ne $ucrs) { next; }
                   5239: 		}
                   5240: 		if ($tsec) {
                   5241: 		    if ($tsec ne $usec) { next; }
                   5242: 		}
                   5243: 		$access=($effect eq 'allow');
                   5244: 		last;
                   5245: 	    }
                   5246: 	    if ($realm eq '' && $role eq '') {
                   5247: 		$access=($effect eq 'allow');
                   5248: 	    }
1.402     bowersj2 5249: 	}
1.341     www      5250:     }
                   5251:     return $access;
                   5252: }
                   5253: 
1.103     harris41 5254: # ------------------------------------------------- Check for a user privilege
1.12      www      5255: 
                   5256: sub allowed {
1.810     raeburn  5257:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5258:     my $ver_orguri=$uri;
1.439     www      5259:     $uri=&deversion($uri);
1.152     www      5260:     my $orguri=$uri;
1.52      www      5261:     $uri=&declutter($uri);
1.809     raeburn  5262: 
1.810     raeburn  5263:     if ($priv eq 'evb') {
                   5264: # Evade communication block restrictions for specified role in a course
                   5265:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5266:             return $1;
                   5267:         } else {
                   5268:             return;
                   5269:         }
                   5270:     }
                   5271: 
1.620     albertel 5272:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5273: # Free bre access to adm and meta resources
1.775     albertel 5274:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5275: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5276: 	&& ($priv eq 'bre')) {
1.14      www      5277: 	return 'F';
1.159     www      5278:     }
                   5279: 
1.545     banghart 5280: # Free bre access to user's own portfolio contents
1.714     raeburn  5281:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5282:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5283: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5284:         my %setters;
                   5285:         my ($startblock,$endblock) = 
                   5286:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5287:         if ($startblock && $endblock) {
                   5288:             return 'B';
                   5289:         } else {
                   5290:             return 'F';
                   5291:         }
1.545     banghart 5292:     }
                   5293: 
1.762     raeburn  5294: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5295:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5296:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5297:         if (exists($env{'request.course.id'})) {
                   5298:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5299:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5300:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5301:                 my $courseprivid=$env{'request.course.id'};
                   5302:                 $courseprivid=~s/\_/\//;
                   5303:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5304:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5305:                     return $1; 
1.762     raeburn  5306:                 } else {
                   5307:                     if ($env{'request.course.sec'}) {
                   5308:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5309:                     }
                   5310:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5311:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5312:                         return $2;
                   5313:                     }
1.714     raeburn  5314:                 }
                   5315:             }
                   5316:         }
                   5317:     }
                   5318: 
1.159     www      5319: # Free bre to public access
                   5320: 
                   5321:     if ($priv eq 'bre') {
1.238     www      5322:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5323: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5324:            return 'F'; 
                   5325:         }
1.238     www      5326:         if ($copyright eq 'priv') {
                   5327:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5328: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5329: 		return '';
                   5330:             }
                   5331:         }
                   5332:         if ($copyright eq 'domain') {
                   5333:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5334: 	    unless (($env{'user.domain'} eq $1) ||
                   5335:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5336: 		return '';
                   5337:             }
1.262     matthew  5338:         }
1.620     albertel 5339:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5340:             # Library role, so allow browsing of resources in this domain.
                   5341:             return 'F';
1.238     www      5342:         }
1.341     www      5343:         if ($copyright eq 'custom') {
                   5344: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5345:         }
1.14      www      5346:     }
1.264     matthew  5347:     # Domain coordinator is trying to create a course
1.620     albertel 5348:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5349:         # uri is the requested domain in this case.
                   5350:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5351:         # a role of dc for the domain in question.
1.620     albertel 5352:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5353:     }
1.29      www      5354: 
1.52      www      5355:     my $thisallowed='';
                   5356:     my $statecond=0;
                   5357:     my $courseprivid='';
                   5358: 
1.1039    raeburn  5359:     my $ownaccess;
1.1043    raeburn  5360:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5361:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5362:         if ($uri eq '') {
                   5363:             $ownaccess = 1;
                   5364:         } else {
                   5365:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5366:                 my $udom = $env{'user.domain'};
                   5367:                 my $uname = $env{'user.name'};
                   5368:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5369:                     $ownaccess = 1;
1.1040    raeburn  5370:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5371:                     unless ($uri =~ m{\.\./}) {
                   5372:                         $ownaccess = 1;
                   5373:                     }
                   5374:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5375:                     my $now = time;
                   5376:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5377:                         my $adom = $1;
                   5378:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5379:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5380:                                 my ($start,$end) = split('.',$env{$key});
                   5381:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5382:                                     $ownaccess = 1;
                   5383:                                     last;
                   5384:                                 }
                   5385:                             }
                   5386:                         }
                   5387:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5388:                         my $adom = $1;
                   5389:                         my $aname = $2;
1.1042    raeburn  5390:                         foreach my $role ('ca','aa') { 
                   5391:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5392:                                 my ($start,$end) =
                   5393:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5394:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5395:                                     $ownaccess = 1;
                   5396:                                     last;
                   5397:                                 }
1.1039    raeburn  5398:                             }
                   5399:                         }
                   5400:                     }
                   5401:                 }
                   5402:             }
                   5403:         }
                   5404:     }
                   5405: 
1.52      www      5406: # Course
                   5407: 
1.620     albertel 5408:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5409:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5410:             $thisallowed.=$1;
                   5411:         }
1.52      www      5412:     }
1.29      www      5413: 
1.52      www      5414: # Domain
                   5415: 
1.620     albertel 5416:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5417:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5418:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5419:             $thisallowed.=$1;
                   5420:         }
1.12      www      5421:     }
1.52      www      5422: 
                   5423: # Course: uri itself is a course
1.66      www      5424:     my $courseuri=$uri;
                   5425:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5426:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5427: 
1.620     albertel 5428:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5429:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5430:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5431:             $thisallowed.=$1;
                   5432:         }
1.12      www      5433:     }
1.29      www      5434: 
1.665     albertel 5435: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5436: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5437:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5438: 	$thisallowed='';
1.671     raeburn  5439:         my ($match)=&is_on_map($uri);
                   5440:         if ($match) {
                   5441:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5442:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5443:                 $thisallowed.=$1;
                   5444:             }
                   5445:         } else {
1.705     albertel 5446:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5447:             if ($refuri) {
                   5448:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5449:                     $thisallowed='F';
1.671     raeburn  5450:                 } else {
                   5451:                     $refuri=&declutter($refuri);
                   5452:                     my ($match) = &is_on_map($refuri);
                   5453:                     if ($match) {
                   5454:                         $thisallowed='F';
                   5455:                     }
1.669     raeburn  5456:                 }
1.671     raeburn  5457:             }
                   5458:         }
1.314     www      5459:     }
1.492     albertel 5460: 
1.766     albertel 5461:     if ($priv eq 'bre'
                   5462: 	&& $thisallowed ne 'F' 
                   5463: 	&& $thisallowed ne '2'
                   5464: 	&& &is_portfolio_url($uri)) {
                   5465: 	$thisallowed = &portfolio_access($uri);
                   5466:     }
                   5467:     
1.52      www      5468: # Full access at system, domain or course-wide level? Exit.
1.29      www      5469:     if ($thisallowed=~/F/) {
                   5470: 	return 'F';
                   5471:     }
                   5472: 
1.52      www      5473: # If this is generating or modifying users, exit with special codes
1.29      www      5474: 
1.643     www      5475:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5476: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5477: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5478: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5479: 	    unless ($auname) { return $thisallowed; }
                   5480: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5481: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5482: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5483: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5484: 	}
1.52      www      5485: 	return $thisallowed;
                   5486:     }
                   5487: #
1.103     harris41 5488: # Gathered so far: system, domain and course wide privileges
1.52      www      5489: #
                   5490: # Course: See if uri or referer is an individual resource that is part of 
                   5491: # the course
                   5492: 
1.620     albertel 5493:     if ($env{'request.course.id'}) {
1.232     www      5494: 
1.620     albertel 5495:        $courseprivid=$env{'request.course.id'};
                   5496:        if ($env{'request.course.sec'}) {
                   5497:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5498:        }
                   5499:        $courseprivid=~s/\_/\//;
                   5500:        my $checkreferer=1;
1.232     www      5501:        my ($match,$cond)=&is_on_map($uri);
                   5502:        if ($match) {
                   5503:            $statecond=$cond;
1.620     albertel 5504:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5505:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5506:                $thisallowed.=$1;
                   5507:                $checkreferer=0;
                   5508:            }
1.29      www      5509:        }
1.83      www      5510:        
1.148     www      5511:        if ($checkreferer) {
1.620     albertel 5512: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5513:             unless ($refuri) {
1.800     albertel 5514:                 foreach my $key (keys(%env)) {
                   5515: 		    if ($key=~/^httpref\..*\*/) {
                   5516: 			my $pattern=$key;
1.156     www      5517:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5518:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5519:                         $pattern=~s/\//\\\//g;
1.152     www      5520:                         if ($orguri=~/$pattern/) {
1.800     albertel 5521: 			    $refuri=$env{$key};
1.148     www      5522:                         }
                   5523:                     }
1.191     harris41 5524:                 }
1.148     www      5525:             }
1.232     www      5526: 
1.148     www      5527:          if ($refuri) { 
1.152     www      5528: 	  $refuri=&declutter($refuri);
1.232     www      5529:           my ($match,$cond)=&is_on_map($refuri);
                   5530:             if ($match) {
                   5531:               my $refstatecond=$cond;
1.620     albertel 5532:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5533:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5534:                   $thisallowed.=$1;
1.53      www      5535:                   $uri=$refuri;
                   5536:                   $statecond=$refstatecond;
1.52      www      5537:               }
                   5538:           }
1.148     www      5539:         }
1.29      www      5540:        }
1.52      www      5541:    }
1.29      www      5542: 
1.52      www      5543: #
1.103     harris41 5544: # Gathered now: all privileges that could apply, and condition number
1.52      www      5545: # 
                   5546: #
                   5547: # Full or no access?
                   5548: #
1.29      www      5549: 
1.52      www      5550:     if ($thisallowed=~/F/) {
                   5551: 	return 'F';
                   5552:     }
1.29      www      5553: 
1.52      www      5554:     unless ($thisallowed) {
                   5555:         return '';
                   5556:     }
1.29      www      5557: 
1.52      www      5558: # Restrictions exist, deal with them
                   5559: #
                   5560: #   C:according to course preferences
                   5561: #   R:according to resource settings
                   5562: #   L:unless locked
                   5563: #   X:according to user session state
                   5564: #
                   5565: 
                   5566: # Possibly locked functionality, check all courses
1.54      www      5567: # Locks might take effect only after 10 minutes cache expiration for other
                   5568: # courses, and 2 minutes for current course
1.52      www      5569: 
                   5570:     my $envkey;
                   5571:     if ($thisallowed=~/L/) {
1.1000    raeburn  5572:         foreach $envkey (keys(%env)) {
1.54      www      5573:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5574:                my $courseid=$2;
                   5575:                my $roleid=$1.'.'.$2;
1.92      www      5576:                $courseid=~s/^\///;
1.54      www      5577:                my $expiretime=600;
1.620     albertel 5578:                if ($env{'request.role'} eq $roleid) {
1.54      www      5579: 		  $expiretime=120;
                   5580:                }
                   5581: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5582:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5583:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5584: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5585:                }
1.620     albertel 5586:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5587:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5588: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5589:                        &log($env{'user.domain'},$env{'user.name'},
                   5590:                             $env{'user.home'},
1.57      www      5591:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5592:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5593:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5594: 		       return '';
                   5595:                    }
                   5596:                }
1.620     albertel 5597:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5598:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5599: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5600:                        &log($env{'user.domain'},$env{'user.name'},
                   5601:                             $env{'user.home'},
1.57      www      5602:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5603:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5604:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5605: 		       return '';
                   5606:                    }
                   5607:                }
                   5608: 	   }
1.29      www      5609:        }
1.52      www      5610:     }
                   5611:    
                   5612: #
                   5613: # Rest of the restrictions depend on selected course
                   5614: #
                   5615: 
1.620     albertel 5616:     unless ($env{'request.course.id'}) {
1.766     albertel 5617: 	if ($thisallowed eq 'A') {
                   5618: 	    return 'A';
1.814     raeburn  5619:         } elsif ($thisallowed eq 'B') {
                   5620:             return 'B';
1.766     albertel 5621: 	} else {
                   5622: 	    return '1';
                   5623: 	}
1.52      www      5624:     }
1.29      www      5625: 
1.52      www      5626: #
                   5627: # Now user is definitely in a course
                   5628: #
1.53      www      5629: 
                   5630: 
                   5631: # Course preferences
                   5632: 
                   5633:    if ($thisallowed=~/C/) {
1.620     albertel 5634:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5635:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5636:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5637: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5638: 	   if ($priv ne 'pch') { 
                   5639: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5640: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5641: 			$env{'request.course.id'});
                   5642: 	   }
1.237     www      5643:            return '';
                   5644:        }
                   5645: 
1.620     albertel 5646:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5647: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5648: 	   if ($priv ne 'pch') { 
                   5649: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5650: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5651: 			$env{'request.course.id'});
                   5652: 	   }
1.54      www      5653:            return '';
                   5654:        }
1.53      www      5655:    }
                   5656: 
                   5657: # Resource preferences
                   5658: 
                   5659:    if ($thisallowed=~/R/) {
1.620     albertel 5660:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5661:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5662: 	   if ($priv ne 'pch') { 
                   5663: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5664: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5665: 	   }
                   5666: 	   return '';
1.54      www      5667:        }
1.53      www      5668:    }
1.30      www      5669: 
1.246     www      5670: # Restricted by state or randomout?
1.30      www      5671: 
1.52      www      5672:    if ($thisallowed=~/X/) {
1.620     albertel 5673:       if ($env{'acc.randomout'}) {
1.579     albertel 5674: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5675:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5676:             return ''; 
                   5677:          }
1.247     www      5678:       }
                   5679:       if (&condval($statecond)) {
1.52      www      5680: 	 return '2';
                   5681:       } else {
                   5682:          return '';
                   5683:       }
                   5684:    }
1.30      www      5685: 
1.766     albertel 5686:     if ($thisallowed eq 'A') {
                   5687: 	return 'A';
1.814     raeburn  5688:     } elsif ($thisallowed eq 'B') {
                   5689:         return 'B';
1.766     albertel 5690:     }
1.52      www      5691:    return 'F';
1.232     www      5692: }
                   5693: 
1.710     albertel 5694: sub split_uri_for_cond {
                   5695:     my $uri=&deversion(&declutter(shift));
                   5696:     my @uriparts=split(/\//,$uri);
                   5697:     my $filename=pop(@uriparts);
                   5698:     my $pathname=join('/',@uriparts);
                   5699:     return ($pathname,$filename);
                   5700: }
1.232     www      5701: # --------------------------------------------------- Is a resource on the map?
                   5702: 
                   5703: sub is_on_map {
1.710     albertel 5704:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5705:     #Trying to find the conditional for the file
1.620     albertel 5706:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5707: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5708:     if ($match) {
1.289     bowersj2 5709: 	return (1,$1);
                   5710:     } else {
1.434     www      5711: 	return (0,0);
1.289     bowersj2 5712:     }
1.12      www      5713: }
                   5714: 
1.427     www      5715: # --------------------------------------------------------- Get symb from alias
                   5716: 
                   5717: sub get_symb_from_alias {
                   5718:     my $symb=shift;
                   5719:     my ($map,$resid,$url)=&decode_symb($symb);
                   5720: # Already is a symb
                   5721:     if ($url) { return $symb; }
                   5722: # Must be an alias
                   5723:     my $aliassymb='';
                   5724:     my %bighash;
1.620     albertel 5725:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5726:                             &GDBM_READER(),0640)) {
                   5727:         my $rid=$bighash{'mapalias_'.$symb};
                   5728: 	if ($rid) {
                   5729: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5730: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5731: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5732: 	}
                   5733:         untie %bighash;
                   5734:     }
                   5735:     return $aliassymb;
                   5736: }
                   5737: 
1.12      www      5738: # ----------------------------------------------------------------- Define Role
                   5739: 
                   5740: sub definerole {
                   5741:   if (allowed('mcr','/')) {
                   5742:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5743:     foreach my $role (split(':',$sysrole)) {
                   5744: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5745:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5746:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5747: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5748:                return "refused:s:$crole&$cqual"; 
                   5749:             }
                   5750:         }
1.191     harris41 5751:     }
1.800     albertel 5752:     foreach my $role (split(':',$domrole)) {
                   5753: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5754:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5755:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5756: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5757:                return "refused:d:$crole&$cqual"; 
                   5758:             }
                   5759:         }
1.191     harris41 5760:     }
1.800     albertel 5761:     foreach my $role (split(':',$courole)) {
                   5762: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5763:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5764:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5765: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5766:                return "refused:c:$crole&$cqual"; 
                   5767:             }
                   5768:         }
1.191     harris41 5769:     }
1.620     albertel 5770:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5771:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5772: 	        "rolesdef_$rolename=".
                   5773:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5774:     return reply($command,$env{'user.home'});
1.12      www      5775:   } else {
                   5776:     return 'refused';
                   5777:   }
1.105     harris41 5778: }
                   5779: 
                   5780: # ---------------- Make a metadata query against the network of library servers
                   5781: 
                   5782: sub metadata_query {
1.244     matthew  5783:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5784:     my %rhash;
1.845     albertel 5785:     my %libserv = &all_library();
1.244     matthew  5786:     my @server_list = (defined($server_array) ? @$server_array
                   5787:                                               : keys(%libserv) );
                   5788:     for my $server (@server_list) {
1.118     harris41 5789: 	unless ($custom or $customshow) {
                   5790: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5791: 	    $rhash{$server}=$reply;
                   5792: 	}
                   5793: 	else {
                   5794: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5795: 			     &escape($custom).':'.&escape($customshow),
                   5796: 			     $server);
                   5797: 	    $rhash{$server}=$reply;
                   5798: 	}
1.112     harris41 5799:     }
1.118     harris41 5800:     return \%rhash;
1.240     www      5801: }
                   5802: 
                   5803: # ----------------------------------------- Send log queries and wait for reply
                   5804: 
                   5805: sub log_query {
                   5806:     my ($uname,$udom,$query,%filters)=@_;
                   5807:     my $uhome=&homeserver($uname,$udom);
                   5808:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5809:     my $uhost=&hostname($uhome);
1.800     albertel 5810:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5811:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5812:                        $uhome);
1.479     albertel 5813:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5814:     return get_query_reply($queryid);
                   5815: }
                   5816: 
1.818     raeburn  5817: # -------------------------- Update MySQL table for portfolio file
                   5818: 
                   5819: sub update_portfolio_table {
1.821     raeburn  5820:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5821:     if ($group ne '') {
                   5822:         $file_name =~s /^\Q$group\E//;
                   5823:     }
1.818     raeburn  5824:     my $homeserver = &homeserver($uname,$udom);
                   5825:     my $queryid=
1.821     raeburn  5826:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5827:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5828:     my $reply = &get_query_reply($queryid);
                   5829:     return $reply;
                   5830: }
                   5831: 
1.899     raeburn  5832: # -------------------------- Update MySQL allusers table
                   5833: 
                   5834: sub update_allusers_table {
                   5835:     my ($uname,$udom,$names) = @_;
                   5836:     my $homeserver = &homeserver($uname,$udom);
                   5837:     my $queryid=
                   5838:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5839:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5840:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5841:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5842:                'generation='.&escape($names->{'generation'}).'%%'.
                   5843:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5844:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5845:     return;
1.899     raeburn  5846: }
                   5847: 
1.508     raeburn  5848: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5849: 
                   5850: sub fetch_enrollment_query {
1.511     raeburn  5851:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5852:     my $homeserver;
1.547     raeburn  5853:     my $maxtries = 1;
1.508     raeburn  5854:     if ($context eq 'automated') {
                   5855:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5856:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5857:     } else {
                   5858:         $homeserver = &homeserver($cnum,$dom);
                   5859:     }
1.838     albertel 5860:     my $host=&hostname($homeserver);
1.506     raeburn  5861:     my $cmd = '';
1.1000    raeburn  5862:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5863:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5864:     }
                   5865:     $cmd =~ s/%%$//;
                   5866:     $cmd = &escape($cmd);
                   5867:     my $query = 'fetchenrollment';
1.620     albertel 5868:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5869:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5870:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5871:         return 'error: '.$queryid;
                   5872:     }
1.506     raeburn  5873:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5874:     my $tries = 1;
                   5875:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5876:         $reply = &get_query_reply($queryid);
                   5877:         $tries ++;
                   5878:     }
1.526     raeburn  5879:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5880:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5881:     } else {
1.901     albertel 5882:         my @responses = split(/:/,$reply);
1.515     raeburn  5883:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5884:             foreach my $line (@responses) {
                   5885:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5886:                 $$replyref{$key} = $value;
                   5887:             }
                   5888:         } else {
1.506     raeburn  5889:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5890:             foreach my $line (@responses) {
                   5891:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5892:                 $$replyref{$key} = $value;
                   5893:                 if ($value > 0) {
1.800     albertel 5894:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5895:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5896:                         my $destname = $pathname.'/'.$filename;
                   5897:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5898:                         if ($xml_classlist =~ /^error/) {
                   5899:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5900:                         } else {
1.506     raeburn  5901:                             if ( open(FILE,">$destname") ) {
                   5902:                                 print FILE &unescape($xml_classlist);
                   5903:                                 close(FILE);
1.526     raeburn  5904:                             } else {
                   5905:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5906:                             }
                   5907:                         }
                   5908:                     }
                   5909:                 }
                   5910:             }
                   5911:         }
                   5912:         return 'ok';
                   5913:     }
                   5914:     return 'error';
                   5915: }
                   5916: 
1.242     www      5917: sub get_query_reply {
                   5918:     my $queryid=shift;
1.240     www      5919:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5920:     my $reply='';
                   5921:     for (1..100) {
                   5922: 	sleep 2;
                   5923:         if (-e $replyfile.'.end') {
1.448     albertel 5924: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5925: 		$reply = join('',<$fh>);
                   5926: 		close($fh);
1.240     www      5927: 	   } else { return 'error: reply_file_error'; }
1.242     www      5928:            return &unescape($reply);
                   5929: 	}
1.240     www      5930:     }
1.242     www      5931:     return 'timeout:'.$queryid;
1.240     www      5932: }
                   5933: 
                   5934: sub courselog_query {
1.241     www      5935: #
                   5936: # possible filters:
                   5937: # url: url or symb
                   5938: # username
                   5939: # domain
                   5940: # action: view, submit, grade
                   5941: # start: timestamp
                   5942: # end: timestamp
                   5943: #
1.240     www      5944:     my (%filters)=@_;
1.620     albertel 5945:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5946:     if ($filters{'url'}) {
                   5947: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5948:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5949:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5950:     }
1.620     albertel 5951:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5953:     return &log_query($cname,$cdom,'courselog',%filters);
                   5954: }
                   5955: 
                   5956: sub userlog_query {
1.858     raeburn  5957: #
                   5958: # possible filters:
                   5959: # action: log check role
                   5960: # start: timestamp
                   5961: # end: timestamp
                   5962: #
1.240     www      5963:     my ($uname,$udom,%filters)=@_;
                   5964:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5965: }
                   5966: 
1.506     raeburn  5967: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5968: 
                   5969: sub auto_run {
1.508     raeburn  5970:     my ($cnum,$cdom) = @_;
1.876     raeburn  5971:     my $response = 0;
                   5972:     my $settings;
                   5973:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5974:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5975:         $settings = $domconfig{'autoenroll'};
                   5976:         if ($settings->{'run'} eq '1') {
                   5977:             $response = 1;
                   5978:         }
                   5979:     } else {
1.934     raeburn  5980:         my $homeserver;
                   5981:         if (&is_course($cdom,$cnum)) {
                   5982:             $homeserver = &homeserver($cnum,$cdom);
                   5983:         } else {
                   5984:             $homeserver = &domain($cdom,'primary');
                   5985:         }
                   5986:         if ($homeserver ne 'no_host') {
                   5987:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5988:         }
1.876     raeburn  5989:     }
1.506     raeburn  5990:     return $response;
                   5991: }
1.776     albertel 5992: 
1.506     raeburn  5993: sub auto_get_sections {
1.508     raeburn  5994:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5995:     my $homeserver;
                   5996:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5997:         $homeserver = &homeserver($cnum,$cdom);
                   5998:     }
                   5999:     if (!defined($homeserver)) { 
                   6000:         if ($cdom =~ /^$match_domain$/) {
                   6001:             $homeserver = &domain($cdom,'primary');
                   6002:         }
                   6003:     }
                   6004:     my @secs;
                   6005:     if (defined($homeserver)) {
                   6006:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6007:         unless ($response eq 'refused') {
                   6008:             @secs = split(/:/,$response);
                   6009:         }
1.506     raeburn  6010:     }
                   6011:     return @secs;
                   6012: }
1.776     albertel 6013: 
1.506     raeburn  6014: sub auto_new_course {
1.508     raeburn  6015:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6016:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6017:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6018:     return $response;
                   6019: }
1.776     albertel 6020: 
1.506     raeburn  6021: sub auto_validate_courseID {
1.508     raeburn  6022:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6023:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6024:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6025:     return $response;
                   6026: }
1.776     albertel 6027: 
1.1007    raeburn  6028: sub auto_validate_instcode {
1.1020    raeburn  6029:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6030:     my ($homeserver,$response);
                   6031:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6032:         $homeserver = &homeserver($cnum,$cdom);
                   6033:     }
                   6034:     if (!defined($homeserver)) {
                   6035:         if ($cdom =~ /^$match_domain$/) {
                   6036:             $homeserver = &domain($cdom,'primary');
                   6037:         }
                   6038:     }
1.1065    raeburn  6039:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6040:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6041:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6042:     return ($outcome,$description);
1.1007    raeburn  6043: }
                   6044: 
1.506     raeburn  6045: sub auto_create_password {
1.873     raeburn  6046:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6047:     my ($homeserver,$response);
1.506     raeburn  6048:     my $create_passwd = 0;
                   6049:     my $authchk = '';
1.873     raeburn  6050:     if ($udom =~ /^$match_domain$/) {
                   6051:         $homeserver = &domain($udom,'primary');
                   6052:     }
                   6053:     if ($homeserver eq '') {
                   6054:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6055:             $homeserver = &homeserver($cnum,$cdom);
                   6056:         }
                   6057:     }
                   6058:     if ($homeserver eq '') {
                   6059:         $authchk = 'nodomain';
1.506     raeburn  6060:     } else {
1.873     raeburn  6061:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6062:         if ($response eq 'refused') {
                   6063:             $authchk = 'refused';
                   6064:         } else {
1.901     albertel 6065:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6066:         }
1.506     raeburn  6067:     }
                   6068:     return ($authparam,$create_passwd,$authchk);
                   6069: }
                   6070: 
1.706     raeburn  6071: sub auto_photo_permission {
                   6072:     my ($cnum,$cdom,$students) = @_;
                   6073:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6074:     my ($outcome,$perm_reqd,$conditions) = 
                   6075: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6076:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6077: 	return (undef,undef);
                   6078:     }
1.706     raeburn  6079:     return ($outcome,$perm_reqd,$conditions);
                   6080: }
                   6081: 
                   6082: sub auto_checkphotos {
                   6083:     my ($uname,$udom,$pid) = @_;
                   6084:     my $homeserver = &homeserver($uname,$udom);
                   6085:     my ($result,$resulttype);
                   6086:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6087: 				   &escape($uname).':'.&escape($pid),
                   6088: 				   $homeserver));
1.709     albertel 6089:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6090: 	return (undef,undef);
                   6091:     }
1.706     raeburn  6092:     if ($outcome) {
                   6093:         ($result,$resulttype) = split(/:/,$outcome);
                   6094:     } 
                   6095:     return ($result,$resulttype);
                   6096: }
                   6097: 
                   6098: sub auto_photochoice {
                   6099:     my ($cnum,$cdom) = @_;
                   6100:     my $homeserver = &homeserver($cnum,$cdom);
                   6101:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6102: 						       &escape($cdom),
                   6103: 						       $homeserver)));
1.709     albertel 6104:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6105: 	return (undef,undef);
                   6106:     }
1.706     raeburn  6107:     return ($update,$comment);
                   6108: }
                   6109: 
                   6110: sub auto_photoupdate {
                   6111:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6112:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6113:     my $host=&hostname($homeserver);
1.706     raeburn  6114:     my $cmd = '';
                   6115:     my $maxtries = 1;
1.800     albertel 6116:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6117:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6118:     }
                   6119:     $cmd =~ s/%%$//;
                   6120:     $cmd = &escape($cmd);
                   6121:     my $query = 'institutionalphotos';
                   6122:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6123:     unless ($queryid=~/^\Q$host\E\_/) {
                   6124:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6125:         return 'error: '.$queryid;
                   6126:     }
                   6127:     my $reply = &get_query_reply($queryid);
                   6128:     my $tries = 1;
                   6129:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6130:         $reply = &get_query_reply($queryid);
                   6131:         $tries ++;
                   6132:     }
                   6133:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6134:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6135:     } else {
                   6136:         my @responses = split(/:/,$reply);
                   6137:         my $outcome = shift(@responses); 
                   6138:         foreach my $item (@responses) {
                   6139:             my ($key,$value) = split(/=/,$item);
                   6140:             $$photo{$key} = $value;
                   6141:         }
                   6142:         return $outcome;
                   6143:     }
                   6144:     return 'error';
                   6145: }
                   6146: 
1.521     raeburn  6147: sub auto_instcode_format {
1.793     albertel 6148:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6149: 	$cat_order) = @_;
1.521     raeburn  6150:     my $courses = '';
1.772     raeburn  6151:     my @homeservers;
1.521     raeburn  6152:     if ($caller eq 'global') {
1.841     albertel 6153: 	my %servers = &get_servers($codedom,'library');
                   6154: 	foreach my $tryserver (keys(%servers)) {
                   6155: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6156: 		push(@homeservers,$tryserver);
                   6157: 	    }
1.584     raeburn  6158:         }
1.1022    raeburn  6159:     } elsif ($caller eq 'requests') {
                   6160:         if ($codedom =~ /^$match_domain$/) {
                   6161:             my $chome = &domain($codedom,'primary');
                   6162:             unless ($chome eq 'no_host') {
                   6163:                 push(@homeservers,$chome);
                   6164:             }
                   6165:         }
1.521     raeburn  6166:     } else {
1.772     raeburn  6167:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6168:     }
1.793     albertel 6169:     foreach my $code (keys(%{$instcodes})) {
                   6170:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6171:     }
                   6172:     chop($courses);
1.772     raeburn  6173:     my $ok_response = 0;
                   6174:     my $response;
                   6175:     while (@homeservers > 0 && $ok_response == 0) {
                   6176:         my $server = shift(@homeservers); 
                   6177:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6178:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6179:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6180: 		split(/:/,$response);
1.772     raeburn  6181:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6182:             push(@{$codetitles},&str2array($codetitles_str));
                   6183:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6184:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6185:             $ok_response = 1;
                   6186:         }
                   6187:     }
                   6188:     if ($ok_response) {
1.521     raeburn  6189:         return 'ok';
1.772     raeburn  6190:     } else {
                   6191:         return $response;
1.521     raeburn  6192:     }
                   6193: }
                   6194: 
1.792     raeburn  6195: sub auto_instcode_defaults {
                   6196:     my ($domain,$returnhash,$code_order) = @_;
                   6197:     my @homeservers;
1.841     albertel 6198: 
                   6199:     my %servers = &get_servers($domain,'library');
                   6200:     foreach my $tryserver (keys(%servers)) {
                   6201: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6202: 	    push(@homeservers,$tryserver);
                   6203: 	}
1.792     raeburn  6204:     }
1.841     albertel 6205: 
1.792     raeburn  6206:     my $response;
1.841     albertel 6207:     foreach my $server (@homeservers) {
1.792     raeburn  6208:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6209:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6210: 	
                   6211: 	foreach my $pair (split(/\&/,$response)) {
                   6212: 	    my ($name,$value)=split(/\=/,$pair);
                   6213: 	    if ($name eq 'code_order') {
                   6214: 		@{$code_order} = split(/\&/,&unescape($value));
                   6215: 	    } else {
                   6216: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6217: 	    }
                   6218: 	}
                   6219: 	return 'ok';
1.792     raeburn  6220:     }
1.841     albertel 6221: 
                   6222:     return $response;
1.1003    raeburn  6223: }
                   6224: 
                   6225: sub auto_possible_instcodes {
1.1007    raeburn  6226:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6227:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6228:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6229:         return;
                   6230:     }
1.1003    raeburn  6231:     my (@homeservers,$uhome);
                   6232:     if (defined(&domain($domain,'primary'))) {
                   6233:         $uhome=&domain($domain,'primary');
                   6234:         push(@homeservers,&domain($domain,'primary'));
                   6235:     } else {
                   6236:         my %servers = &get_servers($domain,'library');
                   6237:         foreach my $tryserver (keys(%servers)) {
                   6238:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6239:                 push(@homeservers,$tryserver);
                   6240:             }
                   6241:         }
                   6242:     }
                   6243:     my $response;
                   6244:     foreach my $server (@homeservers) {
                   6245:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6246:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6247:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6248:             split(':',$response);
                   6249:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6250:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6251:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6252:             my ($name,$value)=split('=',$item);
                   6253:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6254:         }
                   6255:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6256:             my ($name,$value)=split('=',$item);
                   6257:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6258:         }
                   6259:         return 'ok';
                   6260:     }
                   6261:     return $response;
                   6262: }
1.792     raeburn  6263: 
1.1010    raeburn  6264: sub auto_courserequest_checks {
                   6265:     my ($dom) = @_;
1.1020    raeburn  6266:     my ($homeserver,%validations);
                   6267:     if ($dom =~ /^$match_domain$/) {
                   6268:         $homeserver = &domain($dom,'primary');
                   6269:     }
                   6270:     unless ($homeserver eq 'no_host') {
                   6271:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6272:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6273:             my @items = split(/&/,$response);
                   6274:             foreach my $item (@items) {
                   6275:                 my ($key,$value) = split('=',$item);
                   6276:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6277:             }
                   6278:         }
                   6279:     }
1.1010    raeburn  6280:     return %validations; 
                   6281: }
                   6282: 
1.1020    raeburn  6283: sub auto_courserequest_validation {
                   6284:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6285:     my ($homeserver,$response);
                   6286:     if ($dom =~ /^$match_domain$/) {
                   6287:         $homeserver = &domain($dom,'primary');
                   6288:     }
                   6289:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6290:           
1.1020    raeburn  6291:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6292:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6293:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6294:                                     $homeserver));
                   6295:     }
                   6296:     return $response;
                   6297: }
                   6298: 
1.777     albertel 6299: sub auto_validate_class_sec {
1.918     raeburn  6300:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6301:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6302:     my $ownerlist;
                   6303:     if (ref($owners) eq 'ARRAY') {
                   6304:         $ownerlist = join(',',@{$owners});
                   6305:     } else {
                   6306:         $ownerlist = $owners;
                   6307:     }
1.773     raeburn  6308:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6309:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6310:     return $response;
                   6311: }
                   6312: 
1.679     raeburn  6313: # ------------------------------------------------------- Course Group routines
                   6314: 
                   6315: sub get_coursegroups {
1.809     raeburn  6316:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6317:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6318: }
                   6319: 
1.679     raeburn  6320: sub modify_coursegroup {
                   6321:     my ($cdom,$cnum,$groupsettings) = @_;
                   6322:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6323: }
                   6324: 
1.809     raeburn  6325: sub toggle_coursegroup_status {
                   6326:     my ($cdom,$cnum,$group,$action) = @_;
                   6327:     my ($from_namespace,$to_namespace);
                   6328:     if ($action eq 'delete') {
                   6329:         $from_namespace = 'coursegroups';
                   6330:         $to_namespace = 'deleted_groups';
                   6331:     } else {
                   6332:         $from_namespace = 'deleted_groups';
                   6333:         $to_namespace = 'coursegroups';
                   6334:     }
                   6335:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6336:     if (my $tmp = &error(%curr_group)) {
                   6337:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6338:         return ('read error',$tmp);
                   6339:     } else {
                   6340:         my %savedsettings = %curr_group; 
1.809     raeburn  6341:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6342:         my $deloutcome;
                   6343:         if ($result eq 'ok') {
1.809     raeburn  6344:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6345:         } else {
                   6346:             return ('write error',$result);
                   6347:         }
                   6348:         if ($deloutcome eq 'ok') {
                   6349:             return 'ok';
                   6350:         } else {
                   6351:             return ('delete error',$deloutcome);
                   6352:         }
                   6353:     }
                   6354: }
                   6355: 
1.679     raeburn  6356: sub modify_group_roles {
1.957     raeburn  6357:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6358:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6359:     my $role = 'gr/'.&escape($userprivs);
                   6360:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6361:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6362:     if ($result eq 'ok') {
                   6363:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6364:     }
1.679     raeburn  6365:     return $result;
                   6366: }
                   6367: 
                   6368: sub modify_coursegroup_membership {
                   6369:     my ($cdom,$cnum,$membership) = @_;
                   6370:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6371:     return $result;
                   6372: }
                   6373: 
1.682     raeburn  6374: sub get_active_groups {
                   6375:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6376:     my $now = time;
                   6377:     my %groups = ();
                   6378:     foreach my $key (keys(%env)) {
1.811     albertel 6379:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6380:             my ($start,$end) = split(/\./,$env{$key});
                   6381:             if (($end!=0) && ($end<$now)) { next; }
                   6382:             if (($start!=0) && ($start>$now)) { next; }
                   6383:             if ($1 eq $cdom && $2 eq $cnum) {
                   6384:                 $groups{$3} = $env{$key} ;
                   6385:             }
                   6386:         }
                   6387:     }
                   6388:     return %groups;
                   6389: }
                   6390: 
1.683     raeburn  6391: sub get_group_membership {
                   6392:     my ($cdom,$cnum,$group) = @_;
                   6393:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6394: }
                   6395: 
                   6396: sub get_users_groups {
                   6397:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6398:     my @usersgroups;
1.683     raeburn  6399:     my $cachetime=1800;
                   6400: 
                   6401:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6402:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6403:     if (defined($cached)) {
1.734     albertel 6404:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6405:     } else {  
                   6406:         $grouplist = '';
1.816     raeburn  6407:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6408:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6409:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6410:         my $access_end = $env{'course.'.$courseid.
                   6411:                               '.default_enrollment_end_date'};
                   6412:         my $now = time;
                   6413:         foreach my $key (keys(%roleshash)) {
                   6414:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6415:                 my $group = $1;
                   6416:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6417:                     my $start = $2;
                   6418:                     my $end = $1;
                   6419:                     if ($start == -1) { next; } # deleted from group
                   6420:                     if (($start!=0) && ($start>$now)) { next; }
                   6421:                     if (($end!=0) && ($end<$now)) {
                   6422:                         if ($access_end && $access_end < $now) {
                   6423:                             if ($access_end - $end < 86400) {
                   6424:                                 push(@usersgroups,$group);
1.733     raeburn  6425:                             }
                   6426:                         }
1.817     raeburn  6427:                         next;
1.733     raeburn  6428:                     }
1.817     raeburn  6429:                     push(@usersgroups,$group);
1.683     raeburn  6430:                 }
                   6431:             }
                   6432:         }
1.817     raeburn  6433:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6434:         $grouplist = join(':',@usersgroups);
                   6435:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6436:     }
1.733     raeburn  6437:     return @usersgroups;
1.683     raeburn  6438: }
                   6439: 
                   6440: sub devalidate_getgroups_cache {
                   6441:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6442:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6443: 
1.683     raeburn  6444:     my $hashid="$udom:$uname:$courseid";
                   6445:     &devalidate_cache_new('getgroups',$hashid);
                   6446: }
                   6447: 
1.12      www      6448: # ------------------------------------------------------------------ Plain Text
                   6449: 
                   6450: sub plaintext {
1.988     raeburn  6451:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6452:     if ($short =~ m{^cr/}) {
1.758     albertel 6453: 	return (split('/',$short))[-1];
                   6454:     }
1.742     raeburn  6455:     if (!defined($cid)) {
                   6456:         $cid = $env{'request.course.id'};
                   6457:     }
                   6458:     my %rolenames = (
1.1008    raeburn  6459:                       Course    => 'std',
                   6460:                       Community => 'alt1',
1.742     raeburn  6461:                     );
1.1037    raeburn  6462:     if ($cid ne '') {
                   6463:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6464:             unless ($forcedefault) {
                   6465:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6466:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6467:                 return &Apache::lonlocal::mt($roletext);
                   6468:             }
                   6469:         }
                   6470:     }
                   6471:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6472:         (defined($rolenames{$type})) && 
                   6473:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6474:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6475:     } elsif ($cid ne '') {
                   6476:         my $crstype = $env{'course.'.$cid.'.type'};
                   6477:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6478:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6479:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6480:         }
1.742     raeburn  6481:     }
1.1037    raeburn  6482:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6483: }
                   6484: 
                   6485: # ----------------------------------------------------------------- Assign Role
                   6486: 
                   6487: sub assignrole {
1.957     raeburn  6488:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6489:         $context)=@_;
1.21      www      6490:     my $mrole;
                   6491:     if ($role =~ /^cr\//) {
1.393     www      6492:         my $cwosec=$url;
1.811     albertel 6493:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6494: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6495:            my $refused = 1;
                   6496:            if ($context eq 'requestcourses') {
                   6497:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6498:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6499:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6500:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6501:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6502:                            if ($crsenv{'internal.courseowner'} eq
                   6503:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6504:                                $refused = '';
                   6505:                            }
                   6506:                        }
                   6507:                    }
                   6508:                }
                   6509:            }
                   6510:            if ($refused) {
                   6511:                &logthis('Refused custom assignrole: '.
                   6512:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6513:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6514:                return 'refused';
                   6515:            }
1.104     www      6516:         }
1.21      www      6517:         $mrole='cr';
1.678     raeburn  6518:     } elsif ($role =~ /^gr\//) {
                   6519:         my $cwogrp=$url;
1.811     albertel 6520:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6521:         unless (&allowed('mdg',$cwogrp)) {
                   6522:             &logthis('Refused group assignrole: '.
                   6523:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6524:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6525:             return 'refused';
                   6526:         }
                   6527:         $mrole='gr';
1.21      www      6528:     } else {
1.82      www      6529:         my $cwosec=$url;
1.811     albertel 6530:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6531:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6532:             my $refused;
                   6533:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6534:                 if (!(&allowed('c'.$role,$url))) {
                   6535:                     $refused = 1;
                   6536:                 }
                   6537:             } else {
                   6538:                 $refused = 1;
                   6539:             }
1.947     raeburn  6540:             if ($refused) {
1.1045    raeburn  6541:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6542:                 if (!$selfenroll && $context eq 'course') {
                   6543:                     my %crsenv;
                   6544:                     if ($role eq 'cc' || $role eq 'co') {
                   6545:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6546:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6547:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6548:                                 if ($crsenv{'internal.courseowner'} eq 
                   6549:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6550:                                     $refused = '';
                   6551:                                 }
                   6552:                             }
                   6553:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6554:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6555:                                 if ($crsenv{'internal.courseowner'} eq 
                   6556:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6557:                                     $refused = '';
                   6558:                                 }
                   6559:                             }
                   6560:                         }
                   6561:                     }
                   6562:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6563:                     $refused = '';
1.1017    raeburn  6564:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6565:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6566:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6567:                         my $wrongcc;
                   6568:                         if ($cnum =~ /^$match_community$/) {
                   6569:                             $wrongcc = 1 if ($role eq 'cc');
                   6570:                         } else {
                   6571:                             $wrongcc = 1 if ($role eq 'co');
                   6572:                         }
                   6573:                         unless ($wrongcc) {
                   6574:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6575:                             if ($crsenv{'internal.courseowner'} eq 
                   6576:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6577:                                 $refused = '';
                   6578:                             }
1.1017    raeburn  6579:                         }
                   6580:                     }
                   6581:                 }
                   6582:                 if ($refused) {
1.947     raeburn  6583:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6584:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6585: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6586:                     return 'refused';
                   6587:                 }
1.932     raeburn  6588:             }
1.104     www      6589:         }
1.21      www      6590:         $mrole=$role;
                   6591:     }
1.620     albertel 6592:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6593:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6594:     if ($end) { $command.='_'.$end; }
1.21      www      6595:     if ($start) {
                   6596: 	if ($end) { 
1.81      www      6597:            $command.='_'.$start; 
1.21      www      6598:         } else {
1.81      www      6599:            $command.='_0_'.$start;
1.21      www      6600:         }
                   6601:     }
1.739     raeburn  6602:     my $origstart = $start;
                   6603:     my $origend = $end;
1.957     raeburn  6604:     my $delflag;
1.357     www      6605: # actually delete
                   6606:     if ($deleteflag) {
1.373     www      6607: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6608: # modify command to delete the role
1.620     albertel 6609:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6610:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6611: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6612: # set start and finish to negative values for userrolelog
                   6613:            $start=-1;
                   6614:            $end=-1;
1.957     raeburn  6615:            $delflag = 1;
1.357     www      6616:         }
                   6617:     }
                   6618: # send command
1.349     www      6619:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6620: # log new user role if status is ok
1.349     www      6621:     if ($answer eq 'ok') {
1.663     raeburn  6622: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6623: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6624:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6625:         unless ($role =~ /^gr/) {
                   6626:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6627:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6628:         }
1.1053    raeburn  6629:         if ($role eq 'cc') {
                   6630:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6631:         }
1.349     www      6632:     }
                   6633:     return $answer;
1.169     harris41 6634: }
                   6635: 
1.1053    raeburn  6636: sub autoupdate_coowners {
                   6637:     my ($url,$end,$start,$uname,$udom) = @_;
                   6638:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6639:     if (($cdom ne '') && ($cnum ne '')) {
                   6640:         my $now = time;
                   6641:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6642:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6643:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6644:             my $instcode = $coursehash{'internal.coursecode'};
                   6645:             if ($instcode ne '') {
1.1056    raeburn  6646:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6647:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6648:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6649:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6650:                         if ($result eq 'valid') {
                   6651:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6652:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6653:                                     push(@newcoowners,$coowner);
                   6654:                                 }
                   6655:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6656:                                     push(@newcoowners,$uname.':'.$udom);
                   6657:                                 }
                   6658:                                 @newcoowners = sort(@newcoowners);
                   6659:                             } else {
                   6660:                                 push(@newcoowners,$uname.':'.$udom);
                   6661:                             }
                   6662:                         } else {
                   6663:                             if ($coursehash{'internal.co-owners'}) {
                   6664:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6665:                                     unless ($coowner eq $uname.':'.$udom) {
                   6666:                                         push(@newcoowners,$coowner);
                   6667:                                     }
                   6668:                                 }
                   6669:                                 unless (@newcoowners > 0) {
                   6670:                                     $delcoowners = 1;
                   6671:                                     $coowners = '';
                   6672:                                 }
                   6673:                             }
                   6674:                         }
                   6675:                         if (@newcoowners || $delcoowners) {
                   6676:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6677:                                             $delcoowners,@newcoowners);
                   6678:                         }
                   6679:                     }
                   6680:                 }
                   6681:             }
                   6682:         }
                   6683:     }
                   6684: }
                   6685: 
                   6686: sub store_coowners {
                   6687:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6688:     my $cid = $cdom.'_'.$cnum;
                   6689:     my ($coowners,$delresult,$putresult);
                   6690:     if (@newcoowners) {
                   6691:         $coowners = join(',',@newcoowners);
                   6692:         my %coownershash = (
                   6693:                             'internal.co-owners' => $coowners,
                   6694:                            );
                   6695:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6696:         if ($putresult eq 'ok') {
                   6697:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6698:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6699:             }
                   6700:         }
                   6701:     }
                   6702:     if ($delcoowners) {
                   6703:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6704:         if ($delresult eq 'ok') {
                   6705:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6706:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6707:             }
                   6708:         }
                   6709:     }
                   6710:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6711:         my %crsinfo =
                   6712:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6713:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6714:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6715:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6716:         }
                   6717:     }
                   6718: }
                   6719: 
1.169     harris41 6720: # -------------------------------------------------- Modify user authentication
1.197     www      6721: # Overrides without validation
                   6722: 
1.169     harris41 6723: sub modifyuserauth {
                   6724:     my ($udom,$uname,$umode,$upass)=@_;
                   6725:     my $uhome=&homeserver($uname,$udom);
1.197     www      6726:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6727:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6728:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6729:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6730:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6731: 		     &escape($upass),$uhome);
1.620     albertel 6732:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6733:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6734:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6735:     &log($udom,,$uname,$uhome,
1.620     albertel 6736:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6737:                                      $env{'user.name'}.', '.$umode.
1.197     www      6738:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6739:     unless ($reply eq 'ok') {
1.197     www      6740:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6741: 	return 'error: '.$reply;
                   6742:     }   
1.170     harris41 6743:     return 'ok';
1.80      www      6744: }
                   6745: 
1.81      www      6746: # --------------------------------------------------------------- Modify a user
1.80      www      6747: 
1.81      www      6748: sub modifyuser {
1.206     matthew  6749:     my ($udom,    $uname, $uid,
                   6750:         $umode,   $upass, $first,
                   6751:         $middle,  $last,  $gene,
1.1058    raeburn  6752:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6753:     $udom= &LONCAPA::clean_domain($udom);
                   6754:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6755:     my $showcandelete = 'none';
                   6756:     if (ref($candelete) eq 'ARRAY') {
                   6757:         if (@{$candelete} > 0) {
                   6758:             $showcandelete = join(', ',@{$candelete});
                   6759:         }
                   6760:     }
1.81      www      6761:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6762:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6763: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6764:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6765:                                      ' desiredhome not specified'). 
1.620     albertel 6766:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6767:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6768:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6769:     my $newuser;
                   6770:     if ($uhome eq 'no_host') {
                   6771:         $newuser = 1;
                   6772:     }
1.80      www      6773: # ----------------------------------------------------------------- Create User
1.406     albertel 6774:     if (($uhome eq 'no_host') && 
                   6775: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6776:         my $unhome='';
1.844     albertel 6777:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6778:             $unhome = $desiredhome;
1.620     albertel 6779: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6780: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6781:         } else { # load balancing routine for determining $unhome
1.81      www      6782:             my $loadm=10000000;
1.841     albertel 6783: 	    my %servers = &get_servers($udom,'library');
                   6784: 	    foreach my $tryserver (keys(%servers)) {
                   6785: 		my $answer=reply('load',$tryserver);
                   6786: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6787: 		    $loadm=$answer;
                   6788: 		    $unhome=$tryserver;
                   6789: 		}
1.80      www      6790: 	    }
                   6791:         }
                   6792:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6793: 	    return 'error: unable to find a home server for '.$uname.
                   6794:                    ' in domain '.$udom;
1.80      www      6795:         }
                   6796:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6797:                          &escape($upass),$unhome);
                   6798: 	unless ($reply eq 'ok') {
                   6799:             return 'error: '.$reply;
                   6800:         }   
1.230     stredwic 6801:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6802:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6803: 	    return 'error: unable verify users home machine.';
1.80      www      6804:         }
1.209     matthew  6805:     }   # End of creation of new user
1.80      www      6806: # ---------------------------------------------------------------------- Add ID
                   6807:     if ($uid) {
                   6808:        $uid=~tr/A-Z/a-z/;
                   6809:        my %uidhash=&idrget($udom,$uname);
1.196     www      6810:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6811:          && (!$forceid)) {
1.80      www      6812: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6813: 	      return 'error: user id "'.$uid.'" does not match '.
                   6814:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6815:           }
                   6816:        } else {
                   6817: 	  &idput($udom,($uname => $uid));
                   6818:        }
                   6819:     }
                   6820: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6821:     my @tmp=&get('environment',
1.899     raeburn  6822: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6823:                     'permanentemail','inststatus'],
1.134     albertel 6824: 		   $udom,$uname);
1.1075    raeburn  6825:     my (%names,%oldnames);
1.313     matthew  6826:     if ($tmp[0] =~ m/^error:.*/) { 
                   6827:         %names=(); 
                   6828:     } else {
                   6829:         %names = @tmp;
1.1075    raeburn  6830:         %oldnames = %names;
1.313     matthew  6831:     }
1.388     www      6832: #
1.1058    raeburn  6833: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6834: # of users did not contain them), do not overwrite existing values
                   6835: # unless field is in $candelete array ref.  
                   6836: #
                   6837: 
                   6838:     my @fields = ('firstname','middlename','lastname','generation',
                   6839:                   'permanentemail','id');
                   6840:     my %newvalues;
                   6841:     if (ref($candelete) eq 'ARRAY') {
                   6842:         foreach my $field (@fields) {
                   6843:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6844:                 if ($field eq 'firstname') {
                   6845:                     $names{$field} = $first;
                   6846:                 } elsif ($field eq 'middlename') {
                   6847:                     $names{$field} = $middle;
                   6848:                 } elsif ($field eq 'lastname') {
                   6849:                     $names{$field} = $last;
                   6850:                 } elsif ($field eq 'generation') { 
                   6851:                     $names{$field} = $gene;
                   6852:                 } elsif ($field eq 'permanentemail') {
                   6853:                     $names{$field} = $email;
                   6854:                 } elsif ($field eq 'id') {
                   6855:                     $names{$field}  = $uid;
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
1.388     www      6860:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6861:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6862:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6863:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6864:     if ($email) {
                   6865:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6866:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6867:     }
1.899     raeburn  6868:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6869:     if (defined($inststatus)) {
                   6870:         $names{'inststatus'} = '';
                   6871:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6872:         if (ref($usertypes) eq 'HASH') {
                   6873:             my @okstatuses; 
                   6874:             foreach my $item (split(/:/,$inststatus)) {
                   6875:                 if (defined($usertypes->{$item})) {
                   6876:                     push(@okstatuses,$item);  
                   6877:                 }
                   6878:             }
                   6879:             if (@okstatuses) {
                   6880:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6881:             }
                   6882:         }
                   6883:     }
1.1075    raeburn  6884:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6885:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6886:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6887:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6888:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6889:     } else {
                   6890:         $logmsg .= ' during self creation';
                   6891:     }
1.1075    raeburn  6892:     my $changed;
                   6893:     if ($newuser) {
                   6894:         $changed = 1;
                   6895:     } else {
                   6896:         foreach my $field (@fields) {
                   6897:             if ($names{$field} ne $oldnames{$field}) {
                   6898:                 $changed = 1;
                   6899:                 last;
                   6900:             }
                   6901:         }
                   6902:     }
                   6903:     unless ($changed) {
                   6904:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6905:         &logthis($logmsg);
                   6906:         return 'ok';
                   6907:     }
                   6908:     my $reply = &put('environment', \%names, $udom,$uname);
                   6909:     if ($reply ne 'ok') { 
                   6910:         return 'error: '.$reply;
                   6911:     }
1.1087    raeburn  6912:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   6913:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   6914:     }
1.1075    raeburn  6915:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6916:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6917:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6918:     &logthis($logmsg);
1.134     albertel 6919:     return 'ok';
1.80      www      6920: }
                   6921: 
1.81      www      6922: # -------------------------------------------------------------- Modify student
1.80      www      6923: 
1.81      www      6924: sub modifystudent {
                   6925:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6926:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6927:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6928:     if (!$cid) {
1.620     albertel 6929: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6930: 	    return 'not_in_class';
                   6931: 	}
1.80      www      6932:     }
                   6933: # --------------------------------------------------------------- Make the user
1.81      www      6934:     my $reply=&modifyuser
1.209     matthew  6935: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6936:          $desiredhome,$email,$inststatus);
1.80      www      6937:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6938:     # This will cause &modify_student_enrollment to get the uid from the
                   6939:     # students environment
                   6940:     $uid = undef if (!$forceid);
1.455     albertel 6941:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6942: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6943:     return $reply;
                   6944: }
                   6945: 
                   6946: sub modify_student_enrollment {
1.957     raeburn  6947:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6948:     my ($cdom,$cnum,$chome);
                   6949:     if (!$cid) {
1.620     albertel 6950: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6951: 	    return 'not_in_class';
                   6952: 	}
1.620     albertel 6953: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6954: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6955:     } else {
                   6956: 	($cdom,$cnum)=split(/_/,$cid);
                   6957:     }
1.620     albertel 6958:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6959:     if (!$chome) {
1.457     raeburn  6960: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6961:     }
1.455     albertel 6962:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6963:     # Make sure the user exists
1.81      www      6964:     my $uhome=&homeserver($uname,$udom);
                   6965:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6966: 	return 'error: no such user';
                   6967:     }
1.297     matthew  6968:     # Get student data if we were not given enough information
                   6969:     if (!defined($first)  || $first  eq '' || 
                   6970:         !defined($last)   || $last   eq '' || 
                   6971:         !defined($uid)    || $uid    eq '' || 
                   6972:         !defined($middle) || $middle eq '' || 
                   6973:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6974:         # They did not supply us with enough data to enroll the student, so
                   6975:         # we need to pick up more information.
1.297     matthew  6976:         my %tmp = &get('environment',
1.294     matthew  6977:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6978:                        ,$udom,$uname);
                   6979: 
1.800     albertel 6980:         #foreach my $key (keys(%tmp)) {
                   6981:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6982:         #}
1.294     matthew  6983:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6984:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6985:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6986:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6987:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6988:     }
1.556     albertel 6989:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6990:     my $reply=cput('classlist',
                   6991: 		   {"$uname:$udom" => 
1.515     raeburn  6992: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6993: 		   $cdom,$cnum);
1.81      www      6994:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6995: 	return 'error: '.$reply;
1.652     albertel 6996:     } else {
                   6997: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6998:     }
1.297     matthew  6999:     # Add student role to user
1.83      www      7000:     my $uurl='/'.$cid;
1.81      www      7001:     $uurl=~s/\_/\//g;
                   7002:     if ($usec) {
                   7003: 	$uurl.='/'.$usec;
                   7004:     }
1.957     raeburn  7005:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7006: }
                   7007: 
1.556     albertel 7008: sub format_name {
                   7009:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7010:     my $name;
                   7011:     if ($first ne 'lastname') {
                   7012: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7013:     } else {
                   7014: 	if ($lastname=~/\S/) {
                   7015: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7016: 	    $name=~s/\s+,/,/;
                   7017: 	} else {
                   7018: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7019: 	}
                   7020:     }
                   7021:     $name=~s/^\s+//;
                   7022:     $name=~s/\s+$//;
                   7023:     $name=~s/\s+/ /g;
                   7024:     return $name;
                   7025: }
                   7026: 
1.84      www      7027: # ------------------------------------------------- Write to course preferences
                   7028: 
                   7029: sub writecoursepref {
                   7030:     my ($courseid,%prefs)=@_;
                   7031:     $courseid=~s/^\///;
                   7032:     $courseid=~s/\_/\//g;
                   7033:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7034:     my $chome=homeserver($cnum,$cdomain);
                   7035:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7036: 	return 'error: no such course';
                   7037:     }
                   7038:     my $cstring='';
1.800     albertel 7039:     foreach my $pref (keys(%prefs)) {
                   7040: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7041:     }
1.84      www      7042:     $cstring=~s/\&$//;
                   7043:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7044: }
                   7045: 
                   7046: # ---------------------------------------------------------- Make/modify course
                   7047: 
                   7048: sub createcourse {
1.741     raeburn  7049:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7050:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7051:     $url=&declutter($url);
                   7052:     my $cid='';
1.1028    raeburn  7053:     if ($context eq 'requestcourses') {
                   7054:         my $can_create = 0;
                   7055:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7056:         if ($udom eq $ownerdom) {
                   7057:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7058:                                   $context)) {
                   7059:                 $can_create = 1;
                   7060:             }
                   7061:         } else {
                   7062:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7063:                                            $category);
                   7064:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7065:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7066:                 if (@curr > 0) {
                   7067:                     my @options = qw(approval validate autolimit);
                   7068:                     my $optregex = join('|',@options);
                   7069:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7070:                         $can_create = 1;
                   7071:                     }
                   7072:                 }
                   7073:             }
                   7074:         }
                   7075:         if ($can_create) {
                   7076:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7077:                 unless (&allowed('ccc',$udom)) {
                   7078:                     return 'refused'; 
                   7079:                 }
1.1017    raeburn  7080:             }
                   7081:         } else {
                   7082:             return 'refused';
                   7083:         }
1.1028    raeburn  7084:     } elsif (!&allowed('ccc',$udom)) {
                   7085:         return 'refused';
1.84      www      7086:     }
1.1011    raeburn  7087: # --------------------------------------------------------------- Get Unique ID
                   7088:     my $uname;
                   7089:     if ($cnum =~ /^$match_courseid$/) {
                   7090:         my $chome=&homeserver($cnum,$udom,'true');
                   7091:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7092:             $uname = $cnum;
                   7093:         } else {
1.1038    raeburn  7094:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7095:         }
                   7096:     } else {
1.1038    raeburn  7097:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7098:     }
                   7099:     return $uname if ($uname =~ /^error/);
                   7100: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7101:     if (!defined($course_server)) {
                   7102:         if (defined(&domain($udom,'primary'))) {
                   7103:             $course_server = &domain($udom,'primary');
                   7104:         } else {
                   7105:             $course_server = $env{'user.home'}; 
                   7106:         }
                   7107:     }
                   7108:     my %host_servers =
                   7109:         &Apache::lonnet::get_servers($udom,'library');
                   7110:     unless ($host_servers{$course_server}) {
                   7111:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7112:     }
1.84      www      7113: # ------------------------------------------------------------- Make the course
                   7114:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7115:                       $course_server);
1.84      www      7116:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7117:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7118:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7119: 	return 'error: no such course';
                   7120:     }
1.271     www      7121: # ----------------------------------------------------------------- Course made
1.516     raeburn  7122: # log existence
1.1029    raeburn  7123:     my $now = time;
1.918     raeburn  7124:     my $newcourse = {
                   7125:                     $udom.'_'.$uname => {
1.921     raeburn  7126:                                      description => $description,
                   7127:                                      inst_code   => $inst_code,
                   7128:                                      owner       => $course_owner,
                   7129:                                      type        => $crstype,
1.1029    raeburn  7130:                                      creator     => $env{'user.name'}.':'.
                   7131:                                                     $env{'user.domain'},
                   7132:                                      created     => $now,
                   7133:                                      context     => $context,
1.918     raeburn  7134:                                                 },
                   7135:                     };
1.921     raeburn  7136:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7137: # set toplevel url
1.271     www      7138:     my $topurl=$url;
                   7139:     unless ($nonstandard) {
                   7140: # ------------------------------------------ For standard courses, make top url
                   7141:         my $mapurl=&clutter($url);
1.278     www      7142:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7143:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7144: <map>
                   7145: <resource id="1" type="start"></resource>
                   7146: <resource id="2" src="$mapurl"></resource>
                   7147: <resource id="3" type="finish"></resource>
                   7148: <link index="1" from="1" to="2"></link>
                   7149: <link index="2" from="2" to="3"></link>
                   7150: </map>
                   7151: ENDINITMAP
                   7152:         $topurl=&declutter(
1.638     albertel 7153:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7154:                           );
                   7155:     }
                   7156: # ----------------------------------------------------------- Write preferences
1.84      www      7157:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7158:                      ('description'              => $description,
                   7159:                       'url'                      => $topurl,
                   7160:                       'internal.creator'         => $env{'user.name'}.':'.
                   7161:                                                     $env{'user.domain'},
                   7162:                       'internal.created'         => $now,
                   7163:                       'internal.creationcontext' => $context)
                   7164:                     );
1.84      www      7165:     return '/'.$udom.'/'.$uname;
                   7166: }
                   7167: 
1.1011    raeburn  7168: # ------------------------------------------------------------------- Create ID
                   7169: sub generate_coursenum {
1.1038    raeburn  7170:     my ($udom,$crstype) = @_;
1.1011    raeburn  7171:     my $domdesc = &domain($udom);
                   7172:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7173:     my $first;
                   7174:     if ($crstype eq 'Community') {
                   7175:         $first = '0';
                   7176:     } else {
                   7177:         $first = int(1+rand(9)); 
                   7178:     } 
                   7179:     my $uname=$first.
1.1011    raeburn  7180:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7181:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7182:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7183: # ----------------------------------------------- Make sure that does not exist
                   7184:     my $uhome=&homeserver($uname,$udom,'true');
                   7185:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7186:         if ($crstype eq 'Community') {
                   7187:             $first = '0';
                   7188:         } else {
                   7189:             $first = int(1+rand(9));
                   7190:         }
                   7191:         $uname=$first.
1.1011    raeburn  7192:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7193:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7194:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7195:         $uhome=&homeserver($uname,$udom,'true');
                   7196:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7197:             return 'error: unable to generate unique course-ID';
                   7198:         }
                   7199:     }
                   7200:     return $uname;
                   7201: }
                   7202: 
1.813     albertel 7203: sub is_course {
                   7204:     my ($cdom,$cnum) = @_;
                   7205:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7206: 				undef,'.');
1.813     albertel 7207:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7208:         return 1;
                   7209:     }
                   7210:     return 0;
                   7211: }
                   7212: 
1.1015    raeburn  7213: sub store_userdata {
                   7214:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7215:     my $result;
1.1016    raeburn  7216:     if ($datakey ne '') {
1.1013    raeburn  7217:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7218:             if ($udom eq '' || $uname eq '') {
                   7219:                 $udom = $env{'user.domain'};
                   7220:                 $uname = $env{'user.name'};
                   7221:             }
                   7222:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7223:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7224:                 $result = 'error: no_host';
                   7225:             } else {
                   7226:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7227:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7228: 
                   7229:                 my $namevalue='';
                   7230:                 foreach my $key (keys(%{$storehash})) {
                   7231:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7232:                 }
                   7233:                 $namevalue=~s/\&$//;
                   7234:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7235:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7236:             }
                   7237:         } else {
                   7238:             $result = 'error: data to store was not a hash reference'; 
                   7239:         }
                   7240:     } else {
                   7241:         $result= 'error: invalid requestkey'; 
                   7242:     }
                   7243:     return $result;
                   7244: }
                   7245: 
1.21      www      7246: # ---------------------------------------------------------- Assign Custom Role
                   7247: 
                   7248: sub assigncustomrole {
1.957     raeburn  7249:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7250:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7251:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7252: }
                   7253: 
                   7254: # ----------------------------------------------------------------- Revoke Role
                   7255: 
                   7256: sub revokerole {
1.957     raeburn  7257:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7258:     my $now=time;
1.965     raeburn  7259:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7260: }
                   7261: 
                   7262: # ---------------------------------------------------------- Revoke Custom Role
                   7263: 
                   7264: sub revokecustomrole {
1.957     raeburn  7265:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7266:     my $now=time;
1.357     www      7267:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7268:            $deleteflag,$selfenroll,$context);
1.17      www      7269: }
                   7270: 
1.533     banghart 7271: # ------------------------------------------------------------ Disk usage
1.535     albertel 7272: sub diskusage {
1.955     raeburn  7273:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7274:     $directorypath =~ s/\/$//;
                   7275:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7276:                        .&escape($getpropath).':'.&escape($uname).':'
                   7277:                        .&escape($udom),homeserver($uname,$udom));
                   7278:     if ($listing eq 'unknown_cmd') {
                   7279:         if ($getpropath) {
                   7280:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7281:         }
                   7282:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7283:     }
1.514     albertel 7284:     return $listing;
1.512     banghart 7285: }
                   7286: 
1.566     banghart 7287: sub is_locked {
                   7288:     my ($file_name, $domain, $user) = @_;
                   7289:     my @check;
                   7290:     my $is_locked;
                   7291:     push @check, $file_name;
1.613     albertel 7292:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7293: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7294:     my ($tmp)=keys(%locked);
                   7295:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7296:     
1.566     banghart 7297:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7298:         $is_locked = 'false';
                   7299:         foreach my $entry (@{$locked{$file_name}}) {
                   7300:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7301:                $is_locked = 'true';
                   7302:                last;
1.745     raeburn  7303:            }
                   7304:        }
1.566     banghart 7305:     } else {
                   7306:         $is_locked = 'false';
                   7307:     }
                   7308: }
                   7309: 
1.759     albertel 7310: sub declutter_portfile {
                   7311:     my ($file) = @_;
1.833     albertel 7312:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7313:     return $file;
                   7314: }
                   7315: 
1.559     banghart 7316: # ------------------------------------------------------------- Mark as Read Only
                   7317: 
                   7318: sub mark_as_readonly {
                   7319:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7320:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7321:     my ($tmp)=keys(%current_permissions);
                   7322:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7323:     foreach my $file (@{$files}) {
1.759     albertel 7324: 	$file = &declutter_portfile($file);
1.561     banghart 7325:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7326:     }
1.613     albertel 7327:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7328:     return;
                   7329: }
                   7330: 
1.572     banghart 7331: # ------------------------------------------------------------Save Selected Files
                   7332: 
                   7333: sub save_selected_files {
                   7334:     my ($user, $path, @files) = @_;
                   7335:     my $filename = $user."savedfiles";
1.573     banghart 7336:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7337:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7338:     foreach my $file (@files) {
1.620     albertel 7339:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7340:     }
                   7341:     foreach my $file (@other_files) {
1.574     banghart 7342:         print (OUT $file."\n");
1.572     banghart 7343:     }
1.574     banghart 7344:     close (OUT);
1.572     banghart 7345:     return 'ok';
                   7346: }
                   7347: 
1.574     banghart 7348: sub clear_selected_files {
                   7349:     my ($user) = @_;
                   7350:     my $filename = $user."savedfiles";
                   7351:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7352:     print (OUT undef);
                   7353:     close (OUT);
                   7354:     return ("ok");    
                   7355: }
                   7356: 
1.572     banghart 7357: sub files_in_path {
                   7358:     my ($user, $path) = @_;
                   7359:     my $filename = $user."savedfiles";
                   7360:     my %return_files;
1.574     banghart 7361:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7362:     while (my $line_in = <IN>) {
1.574     banghart 7363:         chomp ($line_in);
                   7364:         my @paths_and_file = split (m!/!, $line_in);
                   7365:         my $file_part = pop (@paths_and_file);
                   7366:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7367:         $path_part.='/';
                   7368:         my $path_and_file = $path_part.$file_part;
                   7369:         if ($path_part eq $path) {
                   7370:             $return_files{$file_part}= 'selected';
                   7371:         }
                   7372:     }
1.574     banghart 7373:     close (IN);
                   7374:     return (\%return_files);
1.572     banghart 7375: }
                   7376: 
                   7377: # called in portfolio select mode, to show files selected NOT in current directory
                   7378: sub files_not_in_path {
                   7379:     my ($user, $path) = @_;
                   7380:     my $filename = $user."savedfiles";
                   7381:     my @return_files;
                   7382:     my $path_part;
1.800     albertel 7383:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7384:     while (my $line = <IN>) {
1.572     banghart 7385:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7386:         my @paths_and_file = split(m|/|, $line);
                   7387:         my $file_part = pop(@paths_and_file);
                   7388:         chomp($file_part);
                   7389:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7390:         $path_part .= '/';
                   7391:         my $path_and_file = $path_part.$file_part;
                   7392:         if ($path_part ne $path) {
1.800     albertel 7393:             push(@return_files, ($path_and_file));
1.572     banghart 7394:         }
                   7395:     }
1.800     albertel 7396:     close(OUT);
1.574     banghart 7397:     return (@return_files);
1.572     banghart 7398: }
                   7399: 
1.745     raeburn  7400: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7401: 
1.745     raeburn  7402: sub get_portfile_permissions {
                   7403:     my ($domain,$user) = @_;
1.613     albertel 7404:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7405:     my ($tmp)=keys(%current_permissions);
                   7406:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7407:     return \%current_permissions;
                   7408: }
                   7409: 
                   7410: #---------------------------------------------Get portfolio file access controls
                   7411: 
1.749     raeburn  7412: sub get_access_controls {
1.745     raeburn  7413:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7414:     my %access;
                   7415:     my $real_file = $file;
                   7416:     $file =~ s/\.meta$//;
1.745     raeburn  7417:     if (defined($file)) {
1.749     raeburn  7418:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7419:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7420:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7421:             }
                   7422:         }
1.745     raeburn  7423:     } else {
1.749     raeburn  7424:         foreach my $key (keys(%{$current_permissions})) {
                   7425:             if ($key =~ /\0accesscontrol$/) {
                   7426:                 if (defined($group)) {
                   7427:                     if ($key !~ m-^\Q$group\E/-) {
                   7428:                         next;
                   7429:                     }
                   7430:                 }
                   7431:                 my ($fullpath) = split(/\0/,$key);
                   7432:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7433:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7434:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7435:                     }
                   7436:                 }
                   7437:             }
                   7438:         }
                   7439:     }
                   7440:     return %access;
                   7441: }
                   7442: 
                   7443: sub modify_access_controls {
                   7444:     my ($file_name,$changes,$domain,$user)=@_;
                   7445:     my ($outcome,$deloutcome);
                   7446:     my %store_permissions;
                   7447:     my %new_values;
                   7448:     my %new_control;
                   7449:     my %translation;
                   7450:     my @deletions = ();
                   7451:     my $now = time;
                   7452:     if (exists($$changes{'activate'})) {
                   7453:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7454:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7455:             my $numnew = scalar(@newitems);
                   7456:             for (my $i=0; $i<$numnew; $i++) {
                   7457:                 my $newkey = $newitems[$i];
                   7458:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7459:                 if ($newkey =~ /^\d+:/) { 
                   7460:                     $newkey =~ s/^(\d+)/$newid/;
                   7461:                     $translation{$1} = $newid;
                   7462:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7463:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7464:                     $translation{$1} = $newid;
                   7465:                 }
1.749     raeburn  7466:                 $new_values{$file_name."\0".$newkey} = 
                   7467:                                           $$changes{'activate'}{$newitems[$i]};
                   7468:                 $new_control{$newkey} = $now;
                   7469:             }
                   7470:         }
                   7471:     }
                   7472:     my %todelete;
                   7473:     my %changed_items;
                   7474:     foreach my $action ('delete','update') {
                   7475:         if (exists($$changes{$action})) {
                   7476:             if (ref($$changes{$action}) eq 'HASH') {
                   7477:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7478:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7479:                     if ($action eq 'delete') { 
                   7480:                         $todelete{$itemnum} = 1;
                   7481:                     } else {
                   7482:                         $changed_items{$itemnum} = $key;
                   7483:                     }
                   7484:                 }
1.745     raeburn  7485:             }
                   7486:         }
1.749     raeburn  7487:     }
                   7488:     # get lock on access controls for file.
                   7489:     my $lockhash = {
                   7490:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7491:                                                        ':'.$env{'user.domain'},
                   7492:                    }; 
                   7493:     my $tries = 0;
                   7494:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7495:    
                   7496:     while (($gotlock ne 'ok') && $tries <3) {
                   7497:         $tries ++;
                   7498:         sleep 1;
                   7499:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7500:     }
                   7501:     if ($gotlock eq 'ok') {
                   7502:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7503:         my ($tmp)=keys(%curr_permissions);
                   7504:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7505:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7506:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7507:             if (ref($curr_controls) eq 'HASH') {
                   7508:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7509:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7510:                     if (defined($todelete{$itemnum})) {
                   7511:                         push(@deletions,$file_name."\0".$control_item);
                   7512:                     } else {
                   7513:                         if (defined($changed_items{$itemnum})) {
                   7514:                             $new_control{$changed_items{$itemnum}} = $now;
                   7515:                             push(@deletions,$file_name."\0".$control_item);
                   7516:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7517:                         } else {
                   7518:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7519:                         }
                   7520:                     }
1.745     raeburn  7521:                 }
                   7522:             }
                   7523:         }
1.970     raeburn  7524:         my ($group);
                   7525:         if (&is_course($domain,$user)) {
                   7526:             ($group,my $file) = split(/\//,$file_name,2);
                   7527:         }
1.749     raeburn  7528:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7529:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7530:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7531:         #  remove lock
                   7532:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7533:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7534:         my $sqlresult =
1.970     raeburn  7535:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7536:                                     $group);
1.749     raeburn  7537:     } else {
                   7538:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7539:     }
1.749     raeburn  7540:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7541: }
                   7542: 
1.827     raeburn  7543: sub make_public_indefinitely {
                   7544:     my ($requrl) = @_;
                   7545:     my $now = time;
                   7546:     my $action = 'activate';
                   7547:     my $aclnum = 0;
                   7548:     if (&is_portfolio_url($requrl)) {
                   7549:         my (undef,$udom,$unum,$file_name,$group) =
                   7550:             &parse_portfolio_url($requrl);
                   7551:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7552:         my %access_controls = &get_access_controls($current_perms,
                   7553:                                                    $group,$file_name);
                   7554:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7555:             my ($num,$scope,$end,$start) = 
                   7556:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7557:             if ($scope eq 'public') {
                   7558:                 if ($start <= $now && $end == 0) {
                   7559:                     $action = 'none';
                   7560:                 } else {
                   7561:                     $action = 'update';
                   7562:                     $aclnum = $num;
                   7563:                 }
                   7564:                 last;
                   7565:             }
                   7566:         }
                   7567:         if ($action eq 'none') {
                   7568:              return 'ok';
                   7569:         } else {
                   7570:             my %changes;
                   7571:             my $newend = 0;
                   7572:             my $newstart = $now;
                   7573:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7574:             $changes{$action}{$newkey} = {
                   7575:                 type => 'public',
                   7576:                 time => {
                   7577:                     start => $newstart,
                   7578:                     end   => $newend,
                   7579:                 },
                   7580:             };
                   7581:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7582:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7583:             return $outcome;
                   7584:         }
                   7585:     } else {
                   7586:         return 'invalid';
                   7587:     }
                   7588: }
                   7589: 
1.745     raeburn  7590: #------------------------------------------------------Get Marked as Read Only
                   7591: 
                   7592: sub get_marked_as_readonly {
                   7593:     my ($domain,$user,$what,$group) = @_;
                   7594:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7595:     my @readonly_files;
1.629     banghart 7596:     my $cmp1=$what;
                   7597:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7598:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7599:         if (defined($group)) {
                   7600:             if ($file_name !~ m-^\Q$group\E/-) {
                   7601:                 next;
                   7602:             }
                   7603:         }
1.561     banghart 7604:         if (ref($value) eq "ARRAY"){
                   7605:             foreach my $stored_what (@{$value}) {
1.629     banghart 7606:                 my $cmp2=$stored_what;
1.759     albertel 7607:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7608:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7609:                 }
1.629     banghart 7610:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7611:                     push(@readonly_files, $file_name);
1.745     raeburn  7612:                     last;
1.563     banghart 7613:                 } elsif (!defined($what)) {
                   7614:                     push(@readonly_files, $file_name);
1.745     raeburn  7615:                     last;
1.561     banghart 7616:                 }
                   7617:             }
1.745     raeburn  7618:         }
1.561     banghart 7619:     }
                   7620:     return @readonly_files;
                   7621: }
1.577     banghart 7622: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7623: 
1.577     banghart 7624: sub get_marked_as_readonly_hash {
1.745     raeburn  7625:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7626:     my %readonly_files;
1.745     raeburn  7627:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7628:         if (defined($group)) {
                   7629:             if ($file_name !~ m-^\Q$group\E/-) {
                   7630:                 next;
                   7631:             }
                   7632:         }
1.577     banghart 7633:         if (ref($value) eq "ARRAY"){
                   7634:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7635:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7636:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7637:                         if ($lock_descriptor eq 'graded') {
                   7638:                             $readonly_files{$file_name} = 'graded';
                   7639:                         } elsif ($lock_descriptor eq 'handback') {
                   7640:                             $readonly_files{$file_name} = 'handback';
                   7641:                         } else {
                   7642:                             if (!exists($readonly_files{$file_name})) {
                   7643:                                 $readonly_files{$file_name} = 'locked';
                   7644:                             }
                   7645:                         }
1.745     raeburn  7646:                     }
1.750     banghart 7647:                 } 
1.577     banghart 7648:             }
                   7649:         } 
                   7650:     }
                   7651:     return %readonly_files;
                   7652: }
1.559     banghart 7653: # ------------------------------------------------------------ Unmark as Read Only
                   7654: 
                   7655: sub unmark_as_readonly {
1.629     banghart 7656:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7657:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7658:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7659:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7660:     my $symb_crs = $what;
                   7661:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7662:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7663:     my ($tmp)=keys(%current_permissions);
                   7664:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7665:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7666:     foreach my $file (@readonly_files) {
1.759     albertel 7667: 	my $clean_file = &declutter_portfile($file);
                   7668: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7669: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7670:         my @new_locks;
                   7671:         my @del_keys;
                   7672:         if (ref($current_locks) eq "ARRAY"){
                   7673:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7674:                 my $compare=$locker;
1.749     raeburn  7675:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7676:                     $compare=join('',@{$locker});
1.746     raeburn  7677:                     if ($compare ne $symb_crs) {
                   7678:                         push(@new_locks, $locker);
                   7679:                     }
1.563     banghart 7680:                 }
                   7681:             }
1.650     albertel 7682:             if (scalar(@new_locks) > 0) {
1.563     banghart 7683:                 $current_permissions{$file} = \@new_locks;
                   7684:             } else {
                   7685:                 push(@del_keys, $file);
1.613     albertel 7686:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7687:                 delete($current_permissions{$file});
1.563     banghart 7688:             }
                   7689:         }
1.561     banghart 7690:     }
1.613     albertel 7691:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7692:     return;
                   7693: }
1.512     banghart 7694: 
1.17      www      7695: # ------------------------------------------------------------ Directory lister
                   7696: 
                   7697: sub dirlist {
1.955     raeburn  7698:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7699:     $uri=~s/^\///;
                   7700:     $uri=~s/\/$//;
1.253     stredwic 7701:     my ($udom, $uname);
1.955     raeburn  7702:     if ($getuserdir) {
1.253     stredwic 7703:         $udom = $userdomain;
                   7704:         $uname = $username;
1.955     raeburn  7705:     } else {
                   7706:         (undef,$udom,$uname)=split(/\//,$uri);
                   7707:         if(defined($userdomain)) {
                   7708:             $udom = $userdomain;
                   7709:         }
                   7710:         if(defined($username)) {
                   7711:             $uname = $username;
                   7712:         }
1.253     stredwic 7713:     }
1.955     raeburn  7714:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7715: 
1.955     raeburn  7716:     $dirRoot = $perlvar{'lonDocRoot'};
                   7717:     if (defined($getpropath)) {
                   7718:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7719:         $dirRoot =~ s/\/$//;
1.955     raeburn  7720:     } elsif (defined($getuserdir)) {
                   7721:         my $subdir=$uname.'__';
                   7722:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7723:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7724:                    ."/$udom/$subdir/$uname";
                   7725:     } elsif (defined($alternateRoot)) {
                   7726:         $dirRoot = $alternateRoot;
1.751     banghart 7727:     }
1.253     stredwic 7728: 
                   7729:     if($udom) {
                   7730:         if($uname) {
1.955     raeburn  7731:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7732:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7733:                               .':'.&escape($uname).':'.&escape($udom),
                   7734:                               &homeserver($uname,$udom));
                   7735:             if ($listing eq 'unknown_cmd') {
                   7736:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7737:                                   &homeserver($uname,$udom));
                   7738:             } else {
                   7739:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7740:             }
1.605     matthew  7741:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7742:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7743: 				  &homeserver($uname,$udom));
1.605     matthew  7744:                 @listing_results = split(/:/,$listing);
                   7745:             } else {
                   7746:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7747:             }
                   7748:             return @listing_results;
1.955     raeburn  7749:         } elsif(!$alternateRoot) {
1.800     albertel 7750:             my %allusers;
1.841     albertel 7751: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7752:  	    foreach my $tryserver (keys(%servers)) {
                   7753:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7754:                                   &escape($udom),$tryserver);
                   7755:                 if ($listing eq 'unknown_cmd') {
                   7756: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7757: 				      $udom, $tryserver);
                   7758:                 } else {
                   7759:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7760:                 }
1.841     albertel 7761: 		if ($listing eq 'unknown_cmd') {
                   7762: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7763: 				      $udom, $tryserver);
                   7764: 		    @listing_results = split(/:/,$listing);
                   7765: 		} else {
                   7766: 		    @listing_results =
                   7767: 			map { &unescape($_); } split(/:/,$listing);
                   7768: 		}
                   7769: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7770: 		    $listing_results[0] ne 'empty'       &&
                   7771: 		    $listing_results[0] ne 'con_lost') {
                   7772: 		    foreach my $line (@listing_results) {
                   7773: 			my ($entry) = split(/&/,$line,2);
                   7774: 			$allusers{$entry} = 1;
                   7775: 		    }
                   7776: 		}
1.253     stredwic 7777:             }
                   7778:             my $alluserstr='';
1.800     albertel 7779:             foreach my $user (sort(keys(%allusers))) {
                   7780:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7781:             }
                   7782:             $alluserstr=~s/:$//;
                   7783:             return split(/:/,$alluserstr);
                   7784:         } else {
1.800     albertel 7785:             return ('missing user name');
1.253     stredwic 7786:         }
1.955     raeburn  7787:     } elsif(!defined($getpropath)) {
1.841     albertel 7788:         my @all_domains = sort(&all_domains());
1.955     raeburn  7789:         foreach my $domain (@all_domains) {
                   7790:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7791:         }
                   7792:         return @all_domains;
                   7793:     } else {
1.800     albertel 7794:         return ('missing domain');
1.275     stredwic 7795:     }
                   7796: }
                   7797: 
                   7798: # --------------------------------------------- GetFileTimestamp
                   7799: # This function utilizes dirlist and returns the date stamp for
                   7800: # when it was last modified.  It will also return an error of -1
                   7801: # if an error occurs
                   7802: 
                   7803: sub GetFileTimestamp {
1.955     raeburn  7804:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7805:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7806:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7807:     my ($fileStat) = 
                   7808:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7809:                                  undef,$getuserdir);
1.275     stredwic 7810:     my @stats = split('&', $fileStat);
                   7811:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7812:         # @stats contains first the filename, then the stat output
                   7813:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7814:     } else {
                   7815:         return -1;
1.253     stredwic 7816:     }
1.26      www      7817: }
                   7818: 
1.712     albertel 7819: sub stat_file {
                   7820:     my ($uri) = @_;
1.787     albertel 7821:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7822: 
1.955     raeburn  7823:     my ($udom,$uname,$file);
1.712     albertel 7824:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7825: 	($udom,$uname,$file) =
1.811     albertel 7826: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7827: 	$file = 'userfiles/'.$file;
                   7828:     }
                   7829:     if ($uri =~ m-^/res/-) {
                   7830: 	($udom,$uname) = 
1.807     albertel 7831: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7832: 	$file = $uri;
                   7833:     }
                   7834: 
                   7835:     if (!$udom || !$uname || !$file) {
                   7836: 	# unable to handle the uri
                   7837: 	return ();
                   7838:     }
1.956     raeburn  7839:     my $getpropath;
                   7840:     if ($file =~ /^userfiles\//) {
                   7841:         $getpropath = 1;
                   7842:     }
1.955     raeburn  7843:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7844:     my @stats = split('&', $result);
1.721     banghart 7845:     
1.712     albertel 7846:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7847: 	shift(@stats); #filename is first
                   7848: 	return @stats;
                   7849:     }
                   7850:     return ();
                   7851: }
                   7852: 
1.26      www      7853: # -------------------------------------------------------- Value of a Condition
                   7854: 
1.713     albertel 7855: # gets the value of a specific preevaluated condition
                   7856: #    stored in the string  $env{user.state.<cid>}
                   7857: # or looks up a condition reference in the bighash and if if hasn't
                   7858: # already been evaluated recurses into docondval to get the value of
                   7859: # the condition, then memoizing it to 
                   7860: #   $env{user.state.<cid>.<condition>}
1.40      www      7861: sub directcondval {
                   7862:     my $number=shift;
1.620     albertel 7863:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7864: 	&Apache::lonuserstate::evalstate();
                   7865:     }
1.713     albertel 7866:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7867: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7868:     } elsif ($number =~ /^_/) {
                   7869: 	my $sub_condition;
                   7870: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7871: 		&GDBM_READER(),0640)) {
                   7872: 	    $sub_condition=$bighash{'conditions'.$number};
                   7873: 	    untie(%bighash);
                   7874: 	}
                   7875: 	my $value = &docondval($sub_condition);
1.949     raeburn  7876: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7877: 	return $value;
                   7878:     }
1.620     albertel 7879:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7880:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7881:     } else {
                   7882:        return 2;
                   7883:     }
                   7884: }
                   7885: 
1.713     albertel 7886: # get the collection of conditions for this resource
1.26      www      7887: sub condval {
                   7888:     my $condidx=shift;
1.54      www      7889:     my $allpathcond='';
1.713     albertel 7890:     foreach my $cond (split(/\|/,$condidx)) {
                   7891: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7892: 	    $allpathcond.=
                   7893: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7894: 	}
1.191     harris41 7895:     }
1.54      www      7896:     $allpathcond=~s/\|$//;
1.713     albertel 7897:     return &docondval($allpathcond);
                   7898: }
                   7899: 
                   7900: #evaluates an expression of conditions
                   7901: sub docondval {
                   7902:     my ($allpathcond) = @_;
                   7903:     my $result=0;
                   7904:     if ($env{'request.course.id'}
                   7905: 	&& defined($allpathcond)) {
                   7906: 	my $operand='|';
                   7907: 	my @stack;
                   7908: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7909: 	    if ($chunk eq '(') {
                   7910: 		push @stack,($operand,$result);
                   7911: 	    } elsif ($chunk eq ')') {
                   7912: 		my $before=pop @stack;
                   7913: 		if (pop @stack eq '&') {
                   7914: 		    $result=$result>$before?$before:$result;
                   7915: 		} else {
                   7916: 		    $result=$result>$before?$result:$before;
                   7917: 		}
                   7918: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7919: 		$operand=$chunk;
                   7920: 	    } else {
                   7921: 		my $new=directcondval($chunk);
                   7922: 		if ($operand eq '&') {
                   7923: 		    $result=$result>$new?$new:$result;
                   7924: 		} else {
                   7925: 		    $result=$result>$new?$result:$new;
                   7926: 		}
                   7927: 	    }
                   7928: 	}
1.26      www      7929:     }
                   7930:     return $result;
1.421     albertel 7931: }
                   7932: 
                   7933: # ---------------------------------------------------- Devalidate courseresdata
                   7934: 
                   7935: sub devalidatecourseresdata {
                   7936:     my ($coursenum,$coursedomain)=@_;
                   7937:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7938:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7939: }
                   7940: 
1.763     www      7941: 
1.200     www      7942: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7943: #
                   7944: #  Parameters:
                   7945: #      $coursenum    - Number of the course.
                   7946: #      $coursedomain - Domain at which the course was created.
                   7947: #  Returns:
                   7948: #     A hash of the course parameters along (I think) with timestamps
                   7949: #     and version info.
1.877     foxr     7950: 
1.624     albertel 7951: sub get_courseresdata {
                   7952:     my ($coursenum,$coursedomain)=@_;
1.200     www      7953:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7954:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7955:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7956:     my %dumpreply;
1.417     albertel 7957:     unless (defined($cached)) {
1.624     albertel 7958: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7959: 	$result=\%dumpreply;
1.251     albertel 7960: 	my ($tmp) = keys(%dumpreply);
                   7961: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7962: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7963: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7964: 	    return $tmp;
1.416     albertel 7965: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7966: 	    $result=undef;
1.599     albertel 7967: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7968: 	}
                   7969:     }
1.624     albertel 7970:     return $result;
                   7971: }
                   7972: 
1.633     albertel 7973: sub devalidateuserresdata {
                   7974:     my ($uname,$udom)=@_;
                   7975:     my $hashid="$udom:$uname";
                   7976:     &devalidate_cache_new('userres',$hashid);
                   7977: }
                   7978: 
1.624     albertel 7979: sub get_userresdata {
                   7980:     my ($uname,$udom)=@_;
                   7981:     #most student don\'t have any data set, check if there is some data
                   7982:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7983: 
                   7984:     my $hashid="$udom:$uname";
                   7985:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7986:     if (!defined($cached)) {
                   7987: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7988: 	$result=\%resourcedata;
                   7989: 	&do_cache_new('userres',$hashid,$result,600);
                   7990:     }
                   7991:     my ($tmp)=keys(%$result);
                   7992:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7993: 	return $result;
                   7994:     }
                   7995:     #error 2 occurs when the .db doesn't exist
                   7996:     if ($tmp!~/error: 2 /) {
1.672     albertel 7997: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7998: 		 " Trying to get resource data for ".
                   7999: 		 $uname." at ".$udom.": ".
                   8000: 		 $tmp."</font>");
                   8001:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8002: 	#&EXT_cache_set($udom,$uname);
                   8003: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8004: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8005:     }
                   8006:     return $tmp;
                   8007: }
1.879     foxr     8008: #----------------------------------------------- resdata - return resource data
                   8009: #  Purpose:
                   8010: #    Return resource data for either users or for a course.
                   8011: #  Parameters:
                   8012: #     $name      - Course/user name.
                   8013: #     $domain    - Name of the domain the user/course is registered on.
                   8014: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8015: #     @which     - Array of names of resources desired.
                   8016: #  Returns:
                   8017: #     The value of the first reasource in @which that is found in the
                   8018: #     resource hash.
                   8019: #  Exceptional Conditions:
                   8020: #     If the $type passed in is not valid (not the string 'course' or 
                   8021: #     'user', an undefined  reference is returned.
                   8022: #     If none of the resources are found, an undef is returned
1.624     albertel 8023: sub resdata {
                   8024:     my ($name,$domain,$type,@which)=@_;
                   8025:     my $result;
                   8026:     if ($type eq 'course') {
                   8027: 	$result=&get_courseresdata($name,$domain);
                   8028:     } elsif ($type eq 'user') {
                   8029: 	$result=&get_userresdata($name,$domain);
                   8030:     }
                   8031:     if (!ref($result)) { return $result; }    
1.251     albertel 8032:     foreach my $item (@which) {
1.927     albertel 8033: 	if (defined($result->{$item->[0]})) {
                   8034: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8035: 	}
1.250     albertel 8036:     }
1.291     albertel 8037:     return undef;
1.200     www      8038: }
                   8039: 
1.379     matthew  8040: #
                   8041: # EXT resource caching routines
                   8042: #
                   8043: 
                   8044: sub clear_EXT_cache_status {
1.383     albertel 8045:     &delenv('cache.EXT.');
1.379     matthew  8046: }
                   8047: 
                   8048: sub EXT_cache_status {
                   8049:     my ($target_domain,$target_user) = @_;
1.383     albertel 8050:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8051:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8052:         # We know already the user has no data
                   8053:         return 1;
                   8054:     } else {
                   8055:         return 0;
                   8056:     }
                   8057: }
                   8058: 
                   8059: sub EXT_cache_set {
                   8060:     my ($target_domain,$target_user) = @_;
1.383     albertel 8061:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8062:     #&appenv({$cachename => time});
1.379     matthew  8063: }
                   8064: 
1.28      www      8065: # --------------------------------------------------------- Value of a Variable
1.58      www      8066: sub EXT {
1.715     albertel 8067: 
1.395     albertel 8068:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8069:     unless ($varname) { return ''; }
1.218     albertel 8070:     #get real user name/domain, courseid and symb
                   8071:     my $courseid;
1.359     albertel 8072:     my $publicuser;
1.427     www      8073:     if ($symbparm) {
                   8074: 	$symbparm=&get_symb_from_alias($symbparm);
                   8075:     }
1.218     albertel 8076:     if (!($uname && $udom)) {
1.790     albertel 8077:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8078:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8079:     } else {
1.620     albertel 8080: 	$courseid=$env{'request.course.id'};
1.218     albertel 8081:     }
1.48      www      8082:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8083:     my $rest;
1.320     albertel 8084:     if (defined($therest[0])) {
1.48      www      8085:        $rest=join('.',@therest);
                   8086:     } else {
                   8087:        $rest='';
                   8088:     }
1.320     albertel 8089: 
1.57      www      8090:     my $qualifierrest=$qualifier;
                   8091:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8092:     my $spacequalifierrest=$space;
                   8093:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8094:     if ($realm eq 'user') {
1.48      www      8095: # --------------------------------------------------------------- user.resource
                   8096: 	if ($space eq 'resource') {
1.651     albertel 8097: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8098: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8099: 		 &&
1.744     albertel 8100: 		 ($symbparm eq &symbread()) ) {	
                   8101: 		# if we are in the middle of processing the resource the
                   8102: 		# get the value we are planning on committing
                   8103:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8104:                     return $Apache::lonhomework::results{$qualifierrest};
                   8105:                 } else {
                   8106:                     return $Apache::lonhomework::history{$qualifierrest};
                   8107:                 }
1.335     albertel 8108: 	    } else {
1.359     albertel 8109: 		my %restored;
1.620     albertel 8110: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8111: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8112: 		} else {
                   8113: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8114: 		}
1.335     albertel 8115: 		return $restored{$qualifierrest};
                   8116: 	    }
1.48      www      8117: # ----------------------------------------------------------------- user.access
                   8118:         } elsif ($space eq 'access') {
1.218     albertel 8119: 	    # FIXME - not supporting calls for a specific user
1.48      www      8120:             return &allowed($qualifier,$rest);
                   8121: # ------------------------------------------ user.preferences, user.environment
                   8122:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8123: 	    if (($uname eq $env{'user.name'}) &&
                   8124: 		($udom eq $env{'user.domain'})) {
                   8125: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8126: 	    } else {
1.359     albertel 8127: 		my %returnhash;
                   8128: 		if (!$publicuser) {
                   8129: 		    %returnhash=&userenvironment($udom,$uname,
                   8130: 						 $qualifierrest);
                   8131: 		}
1.218     albertel 8132: 		return $returnhash{$qualifierrest};
                   8133: 	    }
1.48      www      8134: # ----------------------------------------------------------------- user.course
                   8135:         } elsif ($space eq 'course') {
1.218     albertel 8136: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8137:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8138: # ------------------------------------------------------------------- user.role
                   8139:         } elsif ($space eq 'role') {
1.218     albertel 8140: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8141:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8142:             if ($qualifier eq 'value') {
                   8143: 		return $role;
                   8144:             } elsif ($qualifier eq 'extent') {
                   8145:                 return $where;
                   8146:             }
                   8147: # ----------------------------------------------------------------- user.domain
                   8148:         } elsif ($space eq 'domain') {
1.218     albertel 8149:             return $udom;
1.48      www      8150: # ------------------------------------------------------------------- user.name
                   8151:         } elsif ($space eq 'name') {
1.218     albertel 8152:             return $uname;
1.48      www      8153: # ---------------------------------------------------- Any other user namespace
1.29      www      8154:         } else {
1.359     albertel 8155: 	    my %reply;
                   8156: 	    if (!$publicuser) {
                   8157: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8158: 	    }
                   8159: 	    return $reply{$qualifierrest};
1.48      www      8160:         }
1.236     www      8161:     } elsif ($realm eq 'query') {
                   8162: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8163:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8164: 						[$spacequalifierrest]);
1.620     albertel 8165: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8166:    } elsif ($realm eq 'request') {
1.48      www      8167: # ------------------------------------------------------------- request.browser
                   8168:         if ($space eq 'browser') {
1.430     www      8169: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8170: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8171: 		    return 1;
                   8172: 		} else {
                   8173: 		    return 0;
                   8174: 		}
                   8175: 	    } else {
1.620     albertel 8176: 		return $env{'browser.'.$qualifier};
1.430     www      8177: 	    }
1.57      www      8178: # ------------------------------------------------------------ request.filename
                   8179:         } else {
1.620     albertel 8180:             return $env{'request.'.$spacequalifierrest};
1.29      www      8181:         }
1.28      www      8182:     } elsif ($realm eq 'course') {
1.48      www      8183: # ---------------------------------------------------------- course.description
1.620     albertel 8184:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8185:     } elsif ($realm eq 'resource') {
1.165     www      8186: 
1.620     albertel 8187: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8188: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8189: 	}
1.693     albertel 8190: 
                   8191: 	if ($space eq 'title') {
                   8192: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8193: 	    return &gettitle($symbparm);
                   8194: 	}
                   8195: 	
                   8196: 	if ($space eq 'map') {
                   8197: 	    my ($map) = &decode_symb($symbparm);
                   8198: 	    return &symbread($map);
                   8199: 	}
1.905     albertel 8200: 	if ($space eq 'filename') {
                   8201: 	    if ($symbparm) {
                   8202: 		return &clutter((&decode_symb($symbparm))[2]);
                   8203: 	    }
                   8204: 	    return &hreflocation('',$env{'request.filename'});
                   8205: 	}
1.693     albertel 8206: 
                   8207: 	my ($section, $group, @groups);
1.593     albertel 8208: 	my ($courselevelm,$courselevel);
1.539     albertel 8209: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8210: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8211: 
1.218     albertel 8212: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8213: 
1.60      www      8214: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8215: 	    my $symbp=$symbparm;
1.735     albertel 8216: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8217: 
                   8218: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8219: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8220: 
1.620     albertel 8221: 	    if (($env{'user.name'} eq $uname) &&
                   8222: 		($env{'user.domain'} eq $udom)) {
                   8223: 		$section=$env{'request.course.sec'};
1.733     raeburn  8224:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8225:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8226: 	    } else {
1.539     albertel 8227: 		if (! defined($usection)) {
1.551     albertel 8228: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8229: 		} else {
                   8230: 		    $section = $usection;
                   8231: 		}
1.733     raeburn  8232:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8233: 	    }
                   8234: 
                   8235: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8236: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8237: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8238: 
1.593     albertel 8239: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8240: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8241: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8242: 
1.60      www      8243: # ----------------------------------------------------------- first, check user
1.624     albertel 8244: 
                   8245: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8246: 				       ([$courselevelr,'resource'],
                   8247: 					[$courselevelm,'map'     ],
                   8248: 					[$courselevel, 'course'  ]));
1.931     albertel 8249: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8250: 
1.594     albertel 8251: # ------------------------------------------------ second, check some of course
1.684     raeburn  8252:             my $coursereply;
1.691     raeburn  8253:             if (@groups > 0) {
                   8254:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8255:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8256:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8257:             }
1.96      www      8258: 
1.684     raeburn  8259: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8260: 				  $env{'course.'.$courseid.'.domain'},
                   8261: 				  'course',
                   8262: 				  ([$seclevelr,   'resource'],
                   8263: 				   [$seclevelm,   'map'     ],
                   8264: 				   [$seclevel,    'course'  ],
                   8265: 				   [$courselevelr,'resource']));
                   8266: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8267: 
1.60      www      8268: # ------------------------------------------------------ third, check map parms
1.218     albertel 8269: 	    my %parmhash=();
                   8270: 	    my $thisparm='';
                   8271: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8272: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8273: 		    &GDBM_READER(),0640)) {
1.218     albertel 8274: 		$thisparm=$parmhash{$symbparm};
                   8275: 		untie(%parmhash);
                   8276: 	    }
1.927     albertel 8277: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8278: 	}
1.594     albertel 8279: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8280: 
1.218     albertel 8281: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8282: 	my $filename;
                   8283: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8284: 	if ($symbparm) {
1.409     www      8285: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8286: 	} else {
1.620     albertel 8287: 	    $filename=$env{'request.filename'};
1.282     albertel 8288: 	}
                   8289: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8290: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8291: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8292: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8293: 
1.927     albertel 8294: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8295: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8296: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8297: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8298: 				     $env{'course.'.$courseid.'.domain'},
                   8299: 				     'course',
1.927     albertel 8300: 				     ([$courselevelm,'map'   ],
                   8301: 				      [$courselevel, 'course']));
                   8302: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8303: 	}
1.145     www      8304: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8305: 	unless ($space eq '0') {
1.336     albertel 8306: 	    my @parts=split(/_/,$space);
                   8307: 	    my $id=pop(@parts);
                   8308: 	    my $part=join('_',@parts);
                   8309: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8310: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8311: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8312: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8313: 	}
1.395     albertel 8314: 	if ($recurse) { return undef; }
                   8315: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8316: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8317: # ---------------------------------------------------- Any other user namespace
                   8318:     } elsif ($realm eq 'environment') {
                   8319: # ----------------------------------------------------------------- environment
1.620     albertel 8320: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8321: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8322: 	} else {
1.770     albertel 8323: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8324: 		return '';
                   8325: 	    }
1.219     albertel 8326: 	    my %returnhash=&userenvironment($udom,$uname,
                   8327: 					    $spacequalifierrest);
                   8328: 	    return $returnhash{$spacequalifierrest};
                   8329: 	}
1.28      www      8330:     } elsif ($realm eq 'system') {
1.48      www      8331: # ----------------------------------------------------------------- system.time
                   8332: 	if ($space eq 'time') {
                   8333: 	    return time;
                   8334:         }
1.696     albertel 8335:     } elsif ($realm eq 'server') {
                   8336: # ----------------------------------------------------------------- system.time
                   8337: 	if ($space eq 'name') {
                   8338: 	    return $ENV{'SERVER_NAME'};
                   8339:         }
1.28      www      8340:     }
1.48      www      8341:     return '';
1.61      www      8342: }
                   8343: 
1.927     albertel 8344: sub get_reply {
                   8345:     my ($reply_value) = @_;
1.940     raeburn  8346:     if (ref($reply_value) eq 'ARRAY') {
                   8347:         if (wantarray) {
                   8348: 	    return @$reply_value;
                   8349:         }
                   8350:         return $reply_value->[0];
                   8351:     } else {
                   8352:         return $reply_value;
1.927     albertel 8353:     }
                   8354: }
                   8355: 
1.691     raeburn  8356: sub check_group_parms {
                   8357:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8358:     my @groupitems = ();
                   8359:     my $resultitem;
1.927     albertel 8360:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8361:     foreach my $group (@{$groups}) {
                   8362:         foreach my $level (@levels) {
1.927     albertel 8363:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8364:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8365:         }
                   8366:     }
                   8367:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8368:                             $env{'course.'.$courseid.'.domain'},
                   8369:                                      'course',@groupitems);
                   8370:     return $coursereply;
                   8371: }
                   8372: 
                   8373: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8374:     my ($courseid,@groups) = @_;
                   8375:     @groups = sort(@groups);
1.691     raeburn  8376:     return @groups;
                   8377: }
                   8378: 
1.395     albertel 8379: sub packages_tab_default {
                   8380:     my ($uri,$varname)=@_;
                   8381:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8382: 
                   8383:     my (@extension,@specifics,$do_default);
                   8384:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8385: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8386: 	if ($pack_type eq 'default') {
                   8387: 	    $do_default=1;
                   8388: 	} elsif ($pack_type eq 'extension') {
                   8389: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8390: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8391: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8392: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8393: 	}
                   8394:     }
                   8395:     # first look for a package that matches the requested part id
                   8396:     foreach my $package (@specifics) {
                   8397: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8398: 	next if ($pack_part ne $part);
                   8399: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8400: 	    return $packagetab{"$pack_type&$name&default"};
                   8401: 	}
                   8402:     }
                   8403:     # look for any possible matching non extension_ package
                   8404:     foreach my $package (@specifics) {
                   8405: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8406: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8407: 	    return $packagetab{"$pack_type&$name&default"};
                   8408: 	}
1.585     albertel 8409: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8410: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8411: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8412: 	}
                   8413:     }
1.738     albertel 8414:     # look for any posible extension_ match
                   8415:     foreach my $package (@extension) {
                   8416: 	my ($package,$pack_type)=@{$package};
                   8417: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8418: 	    return $packagetab{"$pack_type&$name&default"};
                   8419: 	}
                   8420: 	if (defined($packagetab{$package."&$name&default"})) {
                   8421: 	    return $packagetab{$package."&$name&default"};
                   8422: 	}
                   8423:     }
                   8424:     # look for a global default setting
                   8425:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8426: 	return $packagetab{"default&$name&default"};
                   8427:     }
1.395     albertel 8428:     return undef;
                   8429: }
                   8430: 
1.334     albertel 8431: sub add_prefix_and_part {
                   8432:     my ($prefix,$part)=@_;
                   8433:     my $keyroot;
                   8434:     if (defined($prefix) && $prefix !~ /^__/) {
                   8435: 	# prefix that has a part already
                   8436: 	$keyroot=$prefix;
                   8437:     } elsif (defined($prefix)) {
                   8438: 	# prefix that is missing a part
                   8439: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8440:     } else {
                   8441: 	# no prefix at all
                   8442: 	if (defined($part)) { $keyroot='_'.$part; }
                   8443:     }
                   8444:     return $keyroot;
                   8445: }
                   8446: 
1.71      www      8447: # ---------------------------------------------------------------- Get metadata
                   8448: 
1.599     albertel 8449: my %metaentry;
1.1070    www      8450: my %importedpartids;
1.71      www      8451: sub metadata {
1.176     www      8452:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8453:     $uri=&declutter($uri);
1.288     albertel 8454:     # if it is a non metadata possible uri return quickly
1.529     albertel 8455:     if (($uri eq '') || 
                   8456: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8457: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1089    raeburn  8458:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^\*uploaded\/.+\.sequence$/) ) {
1.924     albertel 8459: 	return undef;
                   8460:     }
                   8461:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8462: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8463: 	return undef;
1.288     albertel 8464:     }
1.73      www      8465:     my $filename=$uri;
                   8466:     $uri=~s/\.meta$//;
1.172     www      8467: #
                   8468: # Is the metadata already cached?
1.177     www      8469: # Look at timestamp of caching
1.172     www      8470: # Everything is cached by the main uri, libraries are never directly cached
                   8471: #
1.428     albertel 8472:     if (!defined($liburi)) {
1.599     albertel 8473: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8474: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8475:     }
                   8476:     {
1.1069    www      8477: # Imported parts would go here
1.1070    www      8478:         my %importedids=();
                   8479:         my @origfileimportpartids=();
1.1069    www      8480:         my $importedparts=0;
1.172     www      8481: #
                   8482: # Is this a recursive call for a library?
                   8483: #
1.599     albertel 8484: #	if (! exists($metacache{$uri})) {
                   8485: #	    $metacache{$uri}={};
                   8486: #	}
1.924     albertel 8487: 	my $cachetime = 60*60;
1.171     www      8488:         if ($liburi) {
                   8489: 	    $liburi=&declutter($liburi);
                   8490:             $filename=$liburi;
1.401     bowersj2 8491:         } else {
1.599     albertel 8492: 	    &devalidate_cache_new('meta',$uri);
                   8493: 	    undef(%metaentry);
1.401     bowersj2 8494: 	}
1.140     www      8495:         my %metathesekeys=();
1.73      www      8496:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8497: 	my $metastring;
1.924     albertel 8498: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8499: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8500: 	    $metastring = 
1.929     albertel 8501: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8502: 					  ('grade_target' => 'meta'));
                   8503: 	    $cachetime = 1; # only want this cached in the child not long term
                   8504: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8505: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8506: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8507: 	    $metastring=&getfile($file);
1.489     albertel 8508: 	}
1.208     albertel 8509:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8510:         my $token;
1.140     www      8511:         undef %metathesekeys;
1.71      www      8512:         while ($token=$parser->get_token) {
1.339     albertel 8513: 	    if ($token->[0] eq 'S') {
                   8514: 		if (defined($token->[2]->{'package'})) {
1.172     www      8515: #
                   8516: # This is a package - get package info
                   8517: #
1.339     albertel 8518: 		    my $package=$token->[2]->{'package'};
                   8519: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8520: 		    if (defined($token->[2]->{'id'})) { 
                   8521: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8522: 		    }
1.599     albertel 8523: 		    if ($metaentry{':packages'}) {
                   8524: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8525: 		    } else {
1.599     albertel 8526: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8527: 		    }
1.736     albertel 8528: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8529: 			my $part=$keyroot;
                   8530: 			$part=~s/^\_//;
1.736     albertel 8531: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8532: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8533: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8534: 			    # ignore package.tab specified default values
                   8535:                             # here &package_tab_default() will fetch those
                   8536: 			    if ($subp eq 'default') { next; }
1.736     albertel 8537: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8538: 			    my $unikey;
                   8539: 			    if ($pack =~ /_0$/) {
                   8540: 				$unikey='parameter_0_'.$name;
                   8541: 				$part=0;
                   8542: 			    } else {
                   8543: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8544: 			    }
1.339     albertel 8545: 			    if ($subp eq 'display') {
                   8546: 				$value.=' [Part: '.$part.']';
                   8547: 			    }
1.599     albertel 8548: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8549: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8550: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8551: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8552: 			    }
1.599     albertel 8553: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8554: 				$metaentry{':'.$unikey}=
                   8555: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8556: 			    }
1.339     albertel 8557: 			}
                   8558: 		    }
                   8559: 		} else {
1.172     www      8560: #
                   8561: # This is not a package - some other kind of start tag
1.339     albertel 8562: #
                   8563: 		    my $entry=$token->[1];
1.1068    www      8564: 		    my $unikey='';
1.175     www      8565: 
1.339     albertel 8566: 		    if ($entry eq 'import') {
1.175     www      8567: #
                   8568: # Importing a library here
1.339     albertel 8569: #
1.1067    www      8570:                         my $location=$parser->get_text('/import');
                   8571:                         my $dir=$filename;
                   8572:                         $dir=~s|[^/]*$||;
                   8573:                         $location=&filelocation($dir,$location);
1.1069    www      8574:                        
1.1068    www      8575:                         my $importmode=$token->[2]->{'importmode'};
                   8576:                         if ($importmode eq 'problem') {
1.1069    www      8577: # Import as problem/response
1.1068    www      8578:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8579:                         } elsif ($importmode eq 'part') {
                   8580: # Import as part(s)
1.1069    www      8581:                            $importedparts=1;
                   8582: # We need to get the original file and the imported file to get the part order correct
                   8583: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8584: # Load and inspect original file
1.1070    www      8585:                            if ($#origfileimportpartids<0) {
                   8586:                               undef(%importedpartids);
                   8587:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8588:                               my $origfile=&getfile($origfilelocation);
                   8589:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8590:                            }
                   8591: 
1.1069    www      8592: # Load and inspect imported file
                   8593:                            my $impfile=&getfile($location);
                   8594:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8595:                            if ($#impfilepartids>=0) {
                   8596: # This problem had parts
1.1070    www      8597:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8598:                            } else {
                   8599: # Importing by turning a single problem into a problem part
                   8600: # It gets the import-tags ID as part-ID
                   8601:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8602:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8603:                            }
1.1068    www      8604:                         } else {
                   8605: # Normal import
                   8606:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8607:                            if (defined($token->[2]->{'id'})) {
                   8608:                               $unikey.='_'.$token->[2]->{'id'};
                   8609:                            }
1.1067    www      8610:                         }
                   8611: 
1.339     albertel 8612: 			if ($depthcount<20) {
1.736     albertel 8613: 			    my $metadata = 
                   8614: 				&metadata($uri,'keys', $location,$unikey,
                   8615: 					  $depthcount+1);
                   8616: 			    foreach my $meta (split(',',$metadata)) {
                   8617: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8618: 				$metathesekeys{$meta}=1;
1.339     albertel 8619: 			    }
1.1068    www      8620: 			
                   8621:                         }
1.1067    www      8622: 		    } else {
                   8623: #
                   8624: # Not importing, some other kind of non-package, non-library start tag
                   8625: # 
                   8626:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8627:                         if (defined($token->[2]->{'id'})) {
                   8628:                             $unikey.='_'.$token->[2]->{'id'};
                   8629:                         }
1.339     albertel 8630: 			if (defined($token->[2]->{'name'})) { 
                   8631: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8632: 			}
                   8633: 			$metathesekeys{$unikey}=1;
1.736     albertel 8634: 			foreach my $param (@{$token->[3]}) {
                   8635: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8636: 				$token->[2]->{$param};
1.339     albertel 8637: 			}
                   8638: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8639: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8640: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8641: 		 # only ws inside the tag, and not in default, so use default
                   8642: 		 # as value
1.599     albertel 8643: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8644: 			} elsif ( $internaltext =~ /\S/ ) {
                   8645: 		  # something interesting inside the tag
                   8646: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8647: 			} else {
1.908     albertel 8648: 		  # no interesting values, don't set a default
1.339     albertel 8649: 			}
1.172     www      8650: # end of not-a-package not-a-library import
1.339     albertel 8651: 		    }
1.172     www      8652: # end of not-a-package start tag
1.339     albertel 8653: 		}
1.172     www      8654: # the next is the end of "start tag"
1.339     albertel 8655: 	    }
                   8656: 	}
1.483     albertel 8657: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8658: 	$extension = lc($extension);
                   8659: 	if ($extension eq 'htm') { $extension='html'; }
                   8660: 
1.737     albertel 8661: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8662: 	    #no specific packages #how's our extension
                   8663: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8664: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8665: 					 \%metathesekeys);
                   8666: 	}
1.883     albertel 8667: 
                   8668: 	if (!exists($metaentry{':packages'})
                   8669: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8670: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8671: 		#no specific packages well let's get default then
                   8672: 		if ($key!~/^default&/) { next; }
1.488     albertel 8673: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8674: 					     \%metathesekeys);
                   8675: 	    }
                   8676: 	}
1.338     www      8677: # are there custom rights to evaluate
1.599     albertel 8678: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8679: 
1.338     www      8680:     #
                   8681:     # Importing a rights file here
1.339     albertel 8682:     #
                   8683: 	    unless ($depthcount) {
1.599     albertel 8684: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8685: 		my $dir=$filename;
                   8686: 		$dir=~s|[^/]*$||;
                   8687: 		$location=&filelocation($dir,$location);
1.736     albertel 8688: 		my $rights_metadata =
                   8689: 		    &metadata($uri,'keys',$location,'_rights',
                   8690: 			      $depthcount+1);
                   8691: 		foreach my $rights (split(',',$rights_metadata)) {
                   8692: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8693: 		    $metathesekeys{$rights}=1;
1.339     albertel 8694: 		}
                   8695: 	    }
                   8696: 	}
1.737     albertel 8697: 	# uniqifiy package listing
                   8698: 	my %seen;
                   8699: 	my @uniq_packages =
                   8700: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8701: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8702: 
1.1070    www      8703:         if ($importedparts) {
                   8704: # We had imported parts and need to rebuild partorder
                   8705:            $metaentry{':partorder'}='';
                   8706:            $metathesekeys{'partorder'}=1;
                   8707:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8708:                if ($origfileimportpartids[$index] eq 'part') {
                   8709: # original part, part of the problem
                   8710:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8711:                } else {
                   8712: # we have imported parts at this position
                   8713:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8714:                }
                   8715:            }
                   8716:            $metaentry{':partorder'}=~s/^\,//;
                   8717:         }
                   8718: 
1.737     albertel 8719: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8720: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8721: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8722: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8723: # this is the end of "was not already recently cached
1.71      www      8724:     }
1.599     albertel 8725:     return $metaentry{':'.$what};
1.261     albertel 8726: }
                   8727: 
1.488     albertel 8728: sub metadata_create_package_def {
1.483     albertel 8729:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8730:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8731:     if ($subp eq 'default') { next; }
                   8732:     
1.599     albertel 8733:     if (defined($metaentry{':packages'})) {
                   8734: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8735:     } else {
1.599     albertel 8736: 	$metaentry{':packages'}=$package;
1.483     albertel 8737:     }
                   8738:     my $value=$packagetab{$key};
                   8739:     my $unikey;
                   8740:     $unikey='parameter_0_'.$name;
1.599     albertel 8741:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8742:     $$metathesekeys{$unikey}=1;
1.599     albertel 8743:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8744: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8745:     }
1.599     albertel 8746:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8747: 	$metaentry{':'.$unikey}=
                   8748: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8749:     }
                   8750: }
                   8751: 
1.261     albertel 8752: sub metadata_generate_part0 {
                   8753:     my ($metadata,$metacache,$uri) = @_;
                   8754:     my %allnames;
1.737     albertel 8755:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8756: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8757: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8758: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8759: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8760: 	    $allnames{$name}=$part;
                   8761: 	  }
                   8762: 	}
                   8763:     }
                   8764:     foreach my $name (keys(%allnames)) {
                   8765:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8766:       my $key=":parameter_0_$name";
1.261     albertel 8767:       $$metacache{"$key.part"}='0';
                   8768:       $$metacache{"$key.name"}=$name;
1.428     albertel 8769:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8770: 					   $allnames{$name}.'_'.$name.
                   8771: 					   '.type'};
1.428     albertel 8772:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8773: 			     '.display'};
1.644     www      8774:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8775:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8776:       $$metacache{"$key.display"}=$olddis;
                   8777:     }
1.71      www      8778: }
                   8779: 
1.764     albertel 8780: # ------------------------------------------------------ Devalidate title cache
                   8781: 
                   8782: sub devalidate_title_cache {
                   8783:     my ($url)=@_;
                   8784:     if (!$env{'request.course.id'}) { return; }
                   8785:     my $symb=&symbread($url);
                   8786:     if (!$symb) { return; }
                   8787:     my $key=$env{'request.course.id'}."\0".$symb;
                   8788:     &devalidate_cache_new('title',$key);
                   8789: }
                   8790: 
1.1014    droeschl 8791: # ------------------------------------------------- Get the title of a course
                   8792: 
                   8793: sub current_course_title {
                   8794:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8795: }
1.301     www      8796: # ------------------------------------------------- Get the title of a resource
                   8797: 
                   8798: sub gettitle {
                   8799:     my $urlsymb=shift;
                   8800:     my $symb=&symbread($urlsymb);
1.534     albertel 8801:     if ($symb) {
1.620     albertel 8802: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8803: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8804: 	if (defined($cached)) { 
                   8805: 	    return $result;
                   8806: 	}
1.534     albertel 8807: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8808: 	my $title='';
1.907     albertel 8809: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8810: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8811: 	} else {
                   8812: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8813: 		    &GDBM_READER(),0640)) {
                   8814: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8815: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8816: 		untie(%bighash);
                   8817: 	    }
1.534     albertel 8818: 	}
                   8819: 	$title=~s/\&colon\;/\:/gs;
                   8820: 	if ($title) {
1.599     albertel 8821: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8822: 	}
                   8823: 	$urlsymb=$url;
                   8824:     }
                   8825:     my $title=&metadata($urlsymb,'title');
                   8826:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8827:     return $title;
1.301     www      8828: }
1.613     albertel 8829: 
1.614     albertel 8830: sub get_slot {
                   8831:     my ($which,$cnum,$cdom)=@_;
                   8832:     if (!$cnum || !$cdom) {
1.790     albertel 8833: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8834: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8835: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8836:     }
1.703     albertel 8837:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8838:     my %slotinfo;
                   8839:     if (exists($remembered{$key})) {
                   8840: 	$slotinfo{$which} = $remembered{$key};
                   8841:     } else {
                   8842: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8843: 	&Apache::lonhomework::showhash(%slotinfo);
                   8844: 	my ($tmp)=keys(%slotinfo);
                   8845: 	if ($tmp=~/^error:/) { return (); }
                   8846: 	$remembered{$key} = $slotinfo{$which};
                   8847:     }
1.616     albertel 8848:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8849: 	return %{$slotinfo{$which}};
                   8850:     }
                   8851:     return $slotinfo{$which};
1.614     albertel 8852: }
1.31      www      8853: # ------------------------------------------------- Update symbolic store links
                   8854: 
                   8855: sub symblist {
                   8856:     my ($mapname,%newhash)=@_;
1.438     www      8857:     $mapname=&deversion(&declutter($mapname));
1.31      www      8858:     my %hash;
1.620     albertel 8859:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8860:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8861:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8862: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8863: 		next if ($url eq 'last_known'
                   8864: 			 && $env{'form.no_update_last_known'});
                   8865: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8866: 						    $newhash{$url}->[1],
                   8867: 						    $newhash{$url}->[0]);
1.191     harris41 8868:             }
1.31      www      8869:             if (untie(%hash)) {
                   8870: 		return 'ok';
                   8871:             }
                   8872:         }
                   8873:     }
                   8874:     return 'error';
1.212     www      8875: }
                   8876: 
                   8877: # --------------------------------------------------------------- Verify a symb
                   8878: 
                   8879: sub symbverify {
1.510     www      8880:     my ($symb,$thisurl)=@_;
                   8881:     my $thisfn=$thisurl;
1.439     www      8882:     $thisfn=&declutter($thisfn);
1.215     www      8883: # direct jump to resource in page or to a sequence - will construct own symbs
                   8884:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8885: # check URL part
1.409     www      8886:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8887: 
1.431     www      8888:     unless ($url eq $thisfn) { return 0; }
1.213     www      8889: 
1.216     www      8890:     $symb=&symbclean($symb);
1.510     www      8891:     $thisurl=&deversion($thisurl);
1.439     www      8892:     $thisfn=&deversion($thisfn);
1.213     www      8893: 
                   8894:     my %bighash;
                   8895:     my $okay=0;
1.431     www      8896: 
1.620     albertel 8897:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8898:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8899:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8900:             $thisurl =~ s/\?.+$//;
                   8901:         }
1.510     www      8902:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8903:         unless ($ids) { 
1.510     www      8904:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8905:         }
                   8906:         if ($ids) {
                   8907: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8908: 	    foreach my $id (split(/\,/,$ids)) {
                   8909: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8910:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8911:                    $symb =~ s/\?.+$//;
                   8912:                }
1.216     www      8913:                if (
                   8914:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8915:    eq $symb) { 
1.620     albertel 8916: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8917: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8918: 		       $okay=1; 
                   8919: 		   }
                   8920: 	       }
1.216     www      8921: 	   }
                   8922:         }
1.213     www      8923: 	untie(%bighash);
                   8924:     }
                   8925:     return $okay;
1.31      www      8926: }
                   8927: 
1.210     www      8928: # --------------------------------------------------------------- Clean-up symb
                   8929: 
                   8930: sub symbclean {
                   8931:     my $symb=shift;
1.568     albertel 8932:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8933: # remove version from map
                   8934:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8935: 
1.210     www      8936: # remove version from URL
                   8937:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8938: 
1.507     www      8939: # remove wrapper
                   8940: 
1.510     www      8941:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8942:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8943:     return $symb;
1.409     www      8944: }
                   8945: 
                   8946: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8947: 
                   8948: sub encode_symb {
                   8949:     my ($map,$resid,$url)=@_;
                   8950:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8951: }
1.409     www      8952: 
                   8953: sub decode_symb {
1.568     albertel 8954:     my $symb=shift;
                   8955:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8956:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8957:     return (&fixversion($map),$resid,&fixversion($url));
                   8958: }
                   8959: 
                   8960: sub fixversion {
                   8961:     my $fn=shift;
1.609     banghart 8962:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8963:     my %bighash;
                   8964:     my $uri=&clutter($fn);
1.620     albertel 8965:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8966: # is this cached?
1.599     albertel 8967:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8968:     if (defined($cached)) { return $result; }
                   8969: # unfortunately not cached, or expired
1.620     albertel 8970:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8971: 	    &GDBM_READER(),0640)) {
                   8972:  	if ($bighash{'version_'.$uri}) {
                   8973:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8974:  	    unless (($version eq 'mostrecent') || 
                   8975: 		    ($version==&getversion($uri))) {
1.440     www      8976:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8977:  	    }
                   8978:  	}
                   8979:  	untie %bighash;
1.413     www      8980:     }
1.599     albertel 8981:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8982: }
                   8983: 
                   8984: sub deversion {
                   8985:     my $url=shift;
                   8986:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8987:     return $url;
1.210     www      8988: }
                   8989: 
1.31      www      8990: # ------------------------------------------------------ Return symb list entry
                   8991: 
                   8992: sub symbread {
1.249     www      8993:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8994:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8995:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8996: # no filename provided? try from environment
1.44      www      8997:     unless ($thisfn) {
1.620     albertel 8998:         if ($env{'request.symb'}) {
                   8999: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9000: 	}
1.620     albertel 9001: 	$thisfn=$env{'request.filename'};
1.44      www      9002:     }
1.569     albertel 9003:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9004: # is that filename actually a symb? Verify, clean, and return
                   9005:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9006: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9007: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9008: 	}
1.242     www      9009:     }
1.44      www      9010:     $thisfn=declutter($thisfn);
1.31      www      9011:     my %hash;
1.37      www      9012:     my %bighash;
                   9013:     my $syval='';
1.620     albertel 9014:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9015:         my $targetfn = $thisfn;
1.609     banghart 9016:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9017:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9018:         }
1.687     albertel 9019: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9020: 	    $targetfn=$1;
                   9021: 	}
1.620     albertel 9022:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9023:                       &GDBM_READER(),0640)) {
1.481     raeburn  9024: 	    $syval=$hash{$targetfn};
1.37      www      9025:             untie(%hash);
                   9026:         }
                   9027: # ---------------------------------------------------------- There was an entry
                   9028:         if ($syval) {
1.601     albertel 9029: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9030: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9031: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9032: 		    #return $env{$cache_str}='';
1.601     albertel 9033: 		#}    
                   9034: 		#$syval.=$1;
                   9035: 	    #}
1.37      www      9036:         } else {
                   9037: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9038:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9039:                             &GDBM_READER(),0640)) {
1.37      www      9040: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9041:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9042:               unless ($ids) { 
                   9043:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9044:               }
                   9045:               unless ($ids) {
                   9046: # alias?
                   9047: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9048:               }
1.37      www      9049:               if ($ids) {
                   9050: # ------------------------------------------------------------------- Has ID(s)
                   9051:                  my @possibilities=split(/\,/,$ids);
1.39      www      9052:                  if ($#possibilities==0) {
                   9053: # ----------------------------------------------- There is only one possibility
1.37      www      9054: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9055: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9056: 						    $resid,$thisfn);
1.249     www      9057:                  } elsif (!$donotrecurse) {
1.39      www      9058: # ------------------------------------------ There is more than one possibility
                   9059:                      my $realpossible=0;
1.800     albertel 9060:                      foreach my $id (@possibilities) {
                   9061: 			 my $file=$bighash{'src_'.$id};
1.39      www      9062:                          if (&allowed('bre',$file)) {
1.800     albertel 9063:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9064:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9065: 				$realpossible++;
1.626     albertel 9066:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9067: 						    $resid,$thisfn);
1.39      www      9068:                             }
                   9069: 			 }
1.191     harris41 9070:                      }
1.39      www      9071: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9072:                  } else {
                   9073:                      $syval='';
1.37      www      9074:                  }
                   9075: 	      }
                   9076:               untie(%bighash)
1.481     raeburn  9077:            }
1.31      www      9078:         }
1.62      www      9079:         if ($syval) {
1.620     albertel 9080: 	    return $env{$cache_str}=$syval;
1.62      www      9081:         }
1.31      www      9082:     }
1.949     raeburn  9083:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9084:     return $env{$cache_str}='';
1.31      www      9085: }
                   9086: 
                   9087: # ---------------------------------------------------------- Return random seed
                   9088: 
1.32      www      9089: sub numval {
                   9090:     my $txt=shift;
                   9091:     $txt=~tr/A-J/0-9/;
                   9092:     $txt=~tr/a-j/0-9/;
                   9093:     $txt=~tr/K-T/0-9/;
                   9094:     $txt=~tr/k-t/0-9/;
                   9095:     $txt=~tr/U-Z/0-5/;
                   9096:     $txt=~tr/u-z/0-5/;
                   9097:     $txt=~s/\D//g;
1.564     albertel 9098:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9099:     return int($txt);
1.368     albertel 9100: }
                   9101: 
1.484     albertel 9102: sub numval2 {
                   9103:     my $txt=shift;
                   9104:     $txt=~tr/A-J/0-9/;
                   9105:     $txt=~tr/a-j/0-9/;
                   9106:     $txt=~tr/K-T/0-9/;
                   9107:     $txt=~tr/k-t/0-9/;
                   9108:     $txt=~tr/U-Z/0-5/;
                   9109:     $txt=~tr/u-z/0-5/;
                   9110:     $txt=~s/\D//g;
                   9111:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9112:     my $total;
                   9113:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9114:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9115:     return int($total);
                   9116: }
                   9117: 
1.575     albertel 9118: sub numval3 {
                   9119:     use integer;
                   9120:     my $txt=shift;
                   9121:     $txt=~tr/A-J/0-9/;
                   9122:     $txt=~tr/a-j/0-9/;
                   9123:     $txt=~tr/K-T/0-9/;
                   9124:     $txt=~tr/k-t/0-9/;
                   9125:     $txt=~tr/U-Z/0-5/;
                   9126:     $txt=~tr/u-z/0-5/;
                   9127:     $txt=~s/\D//g;
                   9128:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9129:     my $total;
                   9130:     foreach my $val (@txts) { $total+=$val; }
                   9131:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9132:     return $total;
                   9133: }
                   9134: 
1.675     albertel 9135: sub digest {
                   9136:     my ($data)=@_;
                   9137:     my $digest=&Digest::MD5::md5($data);
                   9138:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9139:     my ($e,$f);
                   9140:     {
                   9141:         use integer;
                   9142:         $e=($a+$b);
                   9143:         $f=($c+$d);
                   9144:         if ($_64bit) {
                   9145:             $e=(($e<<32)>>32);
                   9146:             $f=(($f<<32)>>32);
                   9147:         }
                   9148:     }
                   9149:     if (wantarray) {
                   9150: 	return ($e,$f);
                   9151:     } else {
                   9152: 	my $g;
                   9153: 	{
                   9154: 	    use integer;
                   9155: 	    $g=($e+$f);
                   9156: 	    if ($_64bit) {
                   9157: 		$g=(($g<<32)>>32);
                   9158: 	    }
                   9159: 	}
                   9160: 	return $g;
                   9161:     }
                   9162: }
                   9163: 
1.368     albertel 9164: sub latest_rnd_algorithm_id {
1.675     albertel 9165:     return '64bit5';
1.366     albertel 9166: }
1.32      www      9167: 
1.503     albertel 9168: sub get_rand_alg {
                   9169:     my ($courseid)=@_;
1.790     albertel 9170:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9171:     if ($courseid) {
1.620     albertel 9172: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9173:     }
                   9174:     return &latest_rnd_algorithm_id();
                   9175: }
                   9176: 
1.562     albertel 9177: sub validCODE {
                   9178:     my ($CODE)=@_;
                   9179:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9180:     return 0;
                   9181: }
                   9182: 
1.491     albertel 9183: sub getCODE {
1.620     albertel 9184:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9185:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9186: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9187: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9188: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9189:     }
                   9190:     return undef;
                   9191: }
                   9192: 
1.31      www      9193: sub rndseed {
1.155     albertel 9194:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9195:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9196:     if (!defined($symb)) {
1.366     albertel 9197: 	unless ($symb=$wsymb) { return time; }
                   9198:     }
                   9199:     if (!$courseid) { $courseid=$wcourseid; }
                   9200:     if (!$domain) { $domain=$wdomain; }
                   9201:     if (!$username) { $username=$wusername }
1.503     albertel 9202:     my $which=&get_rand_alg();
1.803     albertel 9203: 
1.491     albertel 9204:     if (defined(&getCODE())) {
1.675     albertel 9205: 	if ($which eq '64bit5') {
                   9206: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9207: 	} elsif ($which eq '64bit4') {
1.575     albertel 9208: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9209: 	} else {
                   9210: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9211: 	}
1.675     albertel 9212:     } elsif ($which eq '64bit5') {
                   9213: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9214:     } elsif ($which eq '64bit4') {
                   9215: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9216:     } elsif ($which eq '64bit3') {
                   9217: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9218:     } elsif ($which eq '64bit2') {
                   9219: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9220:     } elsif ($which eq '64bit') {
                   9221: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9222:     }
                   9223:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9224: }
                   9225: 
                   9226: sub rndseed_32bit {
                   9227:     my ($symb,$courseid,$domain,$username)=@_;
                   9228:     {
                   9229: 	use integer;
                   9230: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9231: 	my $symbseed=numval($symb) << 22;
                   9232: 	my $namechck=unpack("%32C*",$username) << 17;
                   9233: 	my $nameseed=numval($username) << 12;
                   9234: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9235: 	my $courseseed=unpack("%32C*",$courseid);
                   9236: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9237: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9238: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9239: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9240: 	return $num;
                   9241:     }
                   9242: }
                   9243: 
                   9244: sub rndseed_64bit {
                   9245:     my ($symb,$courseid,$domain,$username)=@_;
                   9246:     {
                   9247: 	use integer;
                   9248: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9249: 	my $symbseed=numval($symb) << 10;
                   9250: 	my $namechck=unpack("%32S*",$username);
                   9251: 	
                   9252: 	my $nameseed=numval($username) << 21;
                   9253: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9254: 	my $courseseed=unpack("%32S*",$courseid);
                   9255: 	
                   9256: 	my $num1=$symbchck+$symbseed+$namechck;
                   9257: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9258: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9259: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9260: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9261: 	return "$num1,$num2";
1.155     albertel 9262:     }
1.366     albertel 9263: }
                   9264: 
1.443     albertel 9265: sub rndseed_64bit2 {
                   9266:     my ($symb,$courseid,$domain,$username)=@_;
                   9267:     {
                   9268: 	use integer;
                   9269: 	# strings need to be an even # of cahracters long, it it is odd the
                   9270:         # last characters gets thrown away
                   9271: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9272: 	my $symbseed=numval($symb) << 10;
                   9273: 	my $namechck=unpack("%32S*",$username.' ');
                   9274: 	
                   9275: 	my $nameseed=numval($username) << 21;
1.501     albertel 9276: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9277: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9278: 	
                   9279: 	my $num1=$symbchck+$symbseed+$namechck;
                   9280: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9281: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9282: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9283: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9284: 	return "$num1,$num2";
                   9285:     }
                   9286: }
                   9287: 
                   9288: sub rndseed_64bit3 {
                   9289:     my ($symb,$courseid,$domain,$username)=@_;
                   9290:     {
                   9291: 	use integer;
                   9292: 	# strings need to be an even # of cahracters long, it it is odd the
                   9293:         # last characters gets thrown away
                   9294: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9295: 	my $symbseed=numval2($symb) << 10;
                   9296: 	my $namechck=unpack("%32S*",$username.' ');
                   9297: 	
                   9298: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9299: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9300: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9301: 	
                   9302: 	my $num1=$symbchck+$symbseed+$namechck;
                   9303: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9304: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9305: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9306: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9307: 	
1.503     albertel 9308: 	return "$num1:$num2";
1.443     albertel 9309:     }
                   9310: }
                   9311: 
1.575     albertel 9312: sub rndseed_64bit4 {
                   9313:     my ($symb,$courseid,$domain,$username)=@_;
                   9314:     {
                   9315: 	use integer;
                   9316: 	# strings need to be an even # of cahracters long, it it is odd the
                   9317:         # last characters gets thrown away
                   9318: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9319: 	my $symbseed=numval3($symb) << 10;
                   9320: 	my $namechck=unpack("%32S*",$username.' ');
                   9321: 	
                   9322: 	my $nameseed=numval3($username) << 21;
                   9323: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9324: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9325: 	
                   9326: 	my $num1=$symbchck+$symbseed+$namechck;
                   9327: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9328: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9329: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9330: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9331: 	
                   9332: 	return "$num1:$num2";
                   9333:     }
                   9334: }
                   9335: 
1.675     albertel 9336: sub rndseed_64bit5 {
                   9337:     my ($symb,$courseid,$domain,$username)=@_;
                   9338:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9339:     return "$num1:$num2";
                   9340: }
                   9341: 
1.366     albertel 9342: sub rndseed_CODE_64bit {
                   9343:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9344:     {
1.366     albertel 9345: 	use integer;
1.443     albertel 9346: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9347: 	my $symbseed=numval2($symb);
1.491     albertel 9348: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9349: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9350: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9351: 	my $num1=$symbseed+$CODEchck;
                   9352: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9353: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9354: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9355: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9356: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9357: 	return "$num1:$num2";
1.366     albertel 9358:     }
                   9359: }
                   9360: 
1.575     albertel 9361: sub rndseed_CODE_64bit4 {
                   9362:     my ($symb,$courseid,$domain,$username)=@_;
                   9363:     {
                   9364: 	use integer;
                   9365: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9366: 	my $symbseed=numval3($symb);
                   9367: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9368: 	my $CODEseed=numval3(&getCODE());
                   9369: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9370: 	my $num1=$symbseed+$CODEchck;
                   9371: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9372: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9373: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9374: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9375: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9376: 	return "$num1:$num2";
                   9377:     }
                   9378: }
                   9379: 
1.675     albertel 9380: sub rndseed_CODE_64bit5 {
                   9381:     my ($symb,$courseid,$domain,$username)=@_;
                   9382:     my $code = &getCODE();
                   9383:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9384:     return "$num1:$num2";
                   9385: }
                   9386: 
1.366     albertel 9387: sub setup_random_from_rndseed {
                   9388:     my ($rndseed)=@_;
1.503     albertel 9389:     if ($rndseed =~/([,:])/) {
                   9390: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9391: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9392:     } else {
                   9393: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9394:     }
1.36      albertel 9395: }
                   9396: 
1.474     albertel 9397: sub latest_receipt_algorithm_id {
1.835     albertel 9398:     return 'receipt3';
1.474     albertel 9399: }
                   9400: 
1.480     www      9401: sub recunique {
                   9402:     my $fucourseid=shift;
                   9403:     my $unique;
1.835     albertel 9404:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9405: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9406: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9407:     } else {
                   9408: 	$unique=$perlvar{'lonReceipt'};
                   9409:     }
                   9410:     return unpack("%32C*",$unique);
                   9411: }
                   9412: 
                   9413: sub recprefix {
                   9414:     my $fucourseid=shift;
                   9415:     my $prefix;
1.835     albertel 9416:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9417: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9418: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9419:     } else {
                   9420: 	$prefix=$perlvar{'lonHostID'};
                   9421:     }
                   9422:     return unpack("%32C*",$prefix);
                   9423: }
                   9424: 
1.76      www      9425: sub ireceipt {
1.474     albertel 9426:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9427: 
                   9428:     my $return =&recprefix($fucourseid).'-';
                   9429: 
                   9430:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9431: 	$env{'request.state'} eq 'construct') {
                   9432: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9433: 	return $return;
                   9434:     }
                   9435: 
1.76      www      9436:     my $cuname=unpack("%32C*",$funame);
                   9437:     my $cudom=unpack("%32C*",$fudom);
                   9438:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9439:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9440:     my $cunique=&recunique($fucourseid);
1.474     albertel 9441:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9442:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9443: 
1.790     albertel 9444: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9445: 			       
                   9446: 	$return.= ($cunique%$cuname+
                   9447: 		   $cunique%$cudom+
                   9448: 		   $cusymb%$cuname+
                   9449: 		   $cusymb%$cudom+
                   9450: 		   $cucourseid%$cuname+
                   9451: 		   $cucourseid%$cudom+
                   9452: 		   $cpart%$cuname+
                   9453: 		   $cpart%$cudom);
                   9454:     } else {
                   9455: 	$return.= ($cunique%$cuname+
                   9456: 		   $cunique%$cudom+
                   9457: 		   $cusymb%$cuname+
                   9458: 		   $cusymb%$cudom+
                   9459: 		   $cucourseid%$cuname+
                   9460: 		   $cucourseid%$cudom);
                   9461:     }
                   9462:     return $return;
1.76      www      9463: }
                   9464: 
                   9465: sub receipt {
1.474     albertel 9466:     my ($part)=@_;
1.790     albertel 9467:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9468:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9469: }
1.260     ng       9470: 
1.790     albertel 9471: sub whichuser {
                   9472:     my ($passedsymb)=@_;
                   9473:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9474:     if (defined($env{'form.grade_symb'})) {
                   9475: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9476: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9477: 	if (!$allowed &&
                   9478: 	    exists($env{'request.course.sec'}) &&
                   9479: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9480: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9481: 			      '/'.$env{'request.course.sec'});
                   9482: 	}
                   9483: 	if ($allowed) {
                   9484: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9485: 	    $courseid=$tmp_courseid;
                   9486: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9487: 	    ($name)=&get_env_multiple('form.grade_username');
                   9488: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9489: 	}
                   9490:     }
                   9491:     if (!$passedsymb) {
                   9492: 	$symb=&symbread();
                   9493:     } else {
                   9494: 	$symb=$passedsymb;
                   9495:     }
                   9496:     $courseid=$env{'request.course.id'};
                   9497:     $domain=$env{'user.domain'};
                   9498:     $name=$env{'user.name'};
                   9499:     if ($name eq 'public' && $domain eq 'public') {
                   9500: 	if (!defined($env{'form.username'})) {
                   9501: 	    $env{'form.username'}.=time.rand(10000000);
                   9502: 	}
                   9503: 	$name.=$env{'form.username'};
                   9504:     }
                   9505:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9506: 
                   9507: }
                   9508: 
1.36      albertel 9509: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9510: # returns either the contents of the file or 
                   9511: # -1 if the file doesn't exist
1.481     raeburn  9512: #
                   9513: # if the target is a file that was uploaded via DOCS, 
                   9514: # a check will be made to see if a current copy exists on the local server,
                   9515: # if it does this will be served, otherwise a copy will be retrieved from
                   9516: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9517: # the local server.   
1.472     albertel 9518: 
1.36      albertel 9519: sub getfile {
1.538     albertel 9520:     my ($file) = @_;
1.609     banghart 9521:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9522:     &repcopy($file);
                   9523:     return &readfile($file);
                   9524: }
                   9525: 
                   9526: sub repcopy_userfile {
                   9527:     my ($file)=@_;
1.609     banghart 9528:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9529:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9530:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9531: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9532:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9533:     if (-e "$file") {
1.828     www      9534: # we already have a local copy, check it out
1.538     albertel 9535: 	my @fileinfo = stat($file);
1.828     www      9536: 	my $rtncode;
                   9537: 	my $info;
1.538     albertel 9538: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9539: 	if ($lwpresp ne 'ok') {
1.828     www      9540: # there is no such file anymore, even though we had a local copy
1.482     albertel 9541: 	    if ($rtncode eq '404') {
1.538     albertel 9542: 		unlink($file);
1.482     albertel 9543: 	    }
                   9544: 	    return -1;
                   9545: 	}
                   9546: 	if ($info < $fileinfo[9]) {
1.828     www      9547: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9548: 	    return 'ok';
1.828     www      9549: 	} else {
                   9550: # the file is outdated, get rid of it
                   9551: 	    unlink($file);
1.482     albertel 9552: 	}
1.828     www      9553:     }
                   9554: # one way or the other, at this point, we don't have the file
                   9555: # construct the correct path for the file
                   9556:     my @parts = ($cdom,$cnum); 
                   9557:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9558: 	push @parts, split(/\//,$1);
                   9559:     }
                   9560:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9561:     foreach my $part (@parts) {
                   9562: 	$path .= '/'.$part;
                   9563: 	if (!-e $path) {
                   9564: 	    mkdir($path,0770);
1.482     albertel 9565: 	}
                   9566:     }
1.828     www      9567: # now the path exists for sure
                   9568: # get a user agent
                   9569:     my $ua=new LWP::UserAgent;
                   9570:     my $transferfile=$file.'.in.transfer';
                   9571: # FIXME: this should flock
                   9572:     if (-e $transferfile) { return 'ok'; }
                   9573:     my $request;
                   9574:     $uri=~s/^\///;
1.980     raeburn  9575:     my $homeserver = &homeserver($cnum,$cdom);
                   9576:     my $protocol = $protocol{$homeserver};
                   9577:     $protocol = 'http' if ($protocol ne 'https');
                   9578:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9579:     my $response=$ua->request($request,$transferfile);
                   9580: # did it work?
                   9581:     if ($response->is_error()) {
                   9582: 	unlink($transferfile);
                   9583: 	&logthis("Userfile repcopy failed for $uri");
                   9584: 	return -1;
                   9585:     }
                   9586: # worked, rename the transfer file
                   9587:     rename($transferfile,$file);
1.607     raeburn  9588:     return 'ok';
1.481     raeburn  9589: }
                   9590: 
1.517     albertel 9591: sub tokenwrapper {
                   9592:     my $uri=shift;
1.980     raeburn  9593:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9594:     $uri=~s|^/||;
1.620     albertel 9595:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9596:     my $token=$1;
1.552     albertel 9597:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9598:     if ($udom && $uname && $file) {
                   9599: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9600:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9601:         my $homeserver = &homeserver($uname,$udom);
                   9602:         my $protocol = $protocol{$homeserver};
                   9603:         $protocol = 'http' if ($protocol ne 'https');
                   9604:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9605:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9606:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9607:     } else {
                   9608:         return '/adm/notfound.html';
                   9609:     }
                   9610: }
                   9611: 
1.828     www      9612: # call with reqtype HEAD: get last modification time
                   9613: # call with reqtype GET: get the file contents
                   9614: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9615: #
1.481     raeburn  9616: sub getuploaded {
                   9617:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9618:     $uri=~s/^\///;
1.980     raeburn  9619:     my $homeserver = &homeserver($cnum,$cdom);
                   9620:     my $protocol = $protocol{$homeserver};
                   9621:     $protocol = 'http' if ($protocol ne 'https');
                   9622:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9623:     my $ua=new LWP::UserAgent;
                   9624:     my $request=new HTTP::Request($reqtype,$uri);
                   9625:     my $response=$ua->request($request);
                   9626:     $$rtncode = $response->code;
1.482     albertel 9627:     if (! $response->is_success()) {
                   9628: 	return 'failed';
                   9629:     }      
                   9630:     if ($reqtype eq 'HEAD') {
1.486     www      9631: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9632:     } elsif ($reqtype eq 'GET') {
                   9633: 	$$info = $response->content;
1.472     albertel 9634:     }
1.482     albertel 9635:     return 'ok';
1.36      albertel 9636: }
                   9637: 
1.481     raeburn  9638: sub readfile {
                   9639:     my $file = shift;
                   9640:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9641:     my $fh;
                   9642:     open($fh,"<$file");
                   9643:     my $a='';
1.800     albertel 9644:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9645:     return $a;
                   9646: }
                   9647: 
1.36      albertel 9648: sub filelocation {
1.590     banghart 9649:     my ($dir,$file) = @_;
                   9650:     my $location;
                   9651:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9652: 
                   9653:     if ($file =~ m-^/adm/-) {
                   9654: 	$file=~s-^/adm/wrapper/-/-;
                   9655: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9656:     }
1.882     albertel 9657: 
1.590     banghart 9658:     if ($file=~m:^/~:) { # is a contruction space reference
                   9659:         $location = $file;
                   9660:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9661:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9662: 	# is a correct contruction space reference
                   9663:         $location = $file;
1.956     raeburn  9664:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9665:         $location = $file;
1.609     banghart 9666:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9667:         my ($udom,$uname,$filename)=
1.811     albertel 9668:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9669:         my $home=&homeserver($uname,$udom);
                   9670:         my $is_me=0;
                   9671:         my @ids=&current_machine_ids();
                   9672:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9673:         if ($is_me) {
1.955     raeburn  9674:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9675:         } else {
                   9676:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9677:   	      $udom.'/'.$uname.'/'.$filename;
                   9678:         }
1.882     albertel 9679:     } elsif ($file =~ m-^/adm/-) {
                   9680: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9681:     } else {
                   9682:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9683:         $file=~s:^/res/:/:;
                   9684:         if ( !( $file =~ m:^/:) ) {
                   9685:             $location = $dir. '/'.$file;
                   9686:         } else {
                   9687:             $location = '/home/httpd/html/res'.$file;
                   9688:         }
1.59      albertel 9689:     }
1.590     banghart 9690:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9691:     while ($location=~m{/\.\./}) {
                   9692: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9693: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9694: 	} else {
                   9695: 	    $location=~ s{/\.\./}{/}g;
                   9696: 	}
                   9697:     } #remove dir/..
1.590     banghart 9698:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9699:     return $location;
1.46      www      9700: }
1.36      albertel 9701: 
1.46      www      9702: sub hreflocation {
                   9703:     my ($dir,$file)=@_;
1.980     raeburn  9704:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9705: 	$file=filelocation($dir,$file);
1.700     albertel 9706:     } elsif ($file=~m-^/adm/-) {
                   9707: 	$file=~s-^/adm/wrapper/-/-;
                   9708: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9709:     }
                   9710:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9711: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9712:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9713: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9714:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9715: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9716: 	    -/uploaded/$1/$2/-x;
1.46      www      9717:     }
1.913     albertel 9718:     if ($file=~ m{^/userfiles/}) {
                   9719: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9720:     }
1.462     albertel 9721:     return $file;
1.465     albertel 9722: }
                   9723: 
                   9724: sub current_machine_domains {
1.853     albertel 9725:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9726: }
                   9727: 
                   9728: sub machine_domains {
                   9729:     my ($hostname) = @_;
1.465     albertel 9730:     my @domains;
1.838     albertel 9731:     my %hostname = &all_hostnames();
1.465     albertel 9732:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9733: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9734: 	if ($hostname eq $name) {
1.844     albertel 9735: 	    push(@domains,&host_domain($id));
1.465     albertel 9736: 	}
                   9737:     }
                   9738:     return @domains;
                   9739: }
                   9740: 
                   9741: sub current_machine_ids {
1.853     albertel 9742:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9743: }
                   9744: 
                   9745: sub machine_ids {
                   9746:     my ($hostname) = @_;
                   9747:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9748:     my @ids;
1.888     albertel 9749:     my %name_to_host = &all_names();
1.889     albertel 9750:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9751: 	return @{ $name_to_host{$hostname} };
                   9752:     }
                   9753:     return;
1.31      www      9754: }
                   9755: 
1.824     raeburn  9756: sub additional_machine_domains {
                   9757:     my @domains;
                   9758:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9759:     while( my $line = <$fh>) {
                   9760:         $line =~ s/\s//g;
                   9761:         push(@domains,$line);
                   9762:     }
                   9763:     return @domains;
                   9764: }
                   9765: 
                   9766: sub default_login_domain {
                   9767:     my $domain = $perlvar{'lonDefDomain'};
                   9768:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9769:     foreach my $posdom (&current_machine_domains(),
                   9770:                         &additional_machine_domains()) {
                   9771:         if (lc($posdom) eq lc($testdomain)) {
                   9772:             $domain=$posdom;
                   9773:             last;
                   9774:         }
                   9775:     }
                   9776:     return $domain;
                   9777: }
                   9778: 
1.31      www      9779: # ------------------------------------------------------------- Declutters URLs
                   9780: 
                   9781: sub declutter {
                   9782:     my $thisfn=shift;
1.569     albertel 9783:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9784:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9785:     $thisfn=~s/^\///;
1.697     albertel 9786:     $thisfn=~s|^adm/wrapper/||;
                   9787:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9788:     $thisfn=~s/^res\///;
1.1032    raeburn  9789:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9790:         $thisfn=~s/\?.+$//;
                   9791:     }
1.268     www      9792:     return $thisfn;
                   9793: }
                   9794: 
                   9795: # ------------------------------------------------------------- Clutter up URLs
                   9796: 
                   9797: sub clutter {
                   9798:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9799:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9800: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9801:        $thisfn='/res'.$thisfn; 
                   9802:     }
1.1031    raeburn  9803:     if ($thisfn !~m|^/adm|) {
                   9804: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9805: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9806: 	} else {
                   9807: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9808: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9809: 	    if ($embstyle eq 'ssi'
                   9810: 		|| ($embstyle eq 'hdn')
                   9811: 		|| ($embstyle eq 'rat')
                   9812: 		|| ($embstyle eq 'prv')
                   9813: 		|| ($embstyle eq 'ign')) {
                   9814: 		#do nothing with these
                   9815: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9816: 		|| ($embstyle eq 'emb')
                   9817: 		|| ($embstyle eq 'wrp')) {
                   9818: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9819: 	    } elsif ($embstyle eq 'unk'
                   9820: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9821: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9822: 	    } else {
1.718     www      9823: #		&logthis("Got a blank emb style");
1.695     albertel 9824: 	    }
1.694     albertel 9825: 	}
                   9826:     }
1.31      www      9827:     return $thisfn;
1.12      www      9828: }
                   9829: 
1.787     albertel 9830: sub clutter_with_no_wrapper {
                   9831:     my $uri = &clutter(shift);
                   9832:     if ($uri =~ m-^/adm/-) {
                   9833: 	$uri =~ s-^/adm/wrapper/-/-;
                   9834: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9835:     }
                   9836:     return $uri;
                   9837: }
                   9838: 
1.557     albertel 9839: sub freeze_escape {
                   9840:     my ($value)=@_;
                   9841:     if (ref($value)) {
                   9842: 	$value=&nfreeze($value);
                   9843: 	return '__FROZEN__'.&escape($value);
                   9844:     }
                   9845:     return &escape($value);
                   9846: }
                   9847: 
1.11      www      9848: 
1.557     albertel 9849: sub thaw_unescape {
                   9850:     my ($value)=@_;
                   9851:     if ($value =~ /^__FROZEN__/) {
                   9852: 	substr($value,0,10,undef);
                   9853: 	$value=&unescape($value);
                   9854: 	return &thaw($value);
                   9855:     }
                   9856:     return &unescape($value);
                   9857: }
                   9858: 
1.436     albertel 9859: sub correct_line_ends {
                   9860:     my ($result)=@_;
                   9861:     $$result =~s/\r\n/\n/mg;
                   9862:     $$result =~s/\r/\n/mg;
1.415     albertel 9863: }
1.1       albertel 9864: # ================================================================ Main Program
                   9865: 
1.184     www      9866: sub goodbye {
1.204     albertel 9867:    &logthis("Starting Shut down");
1.443     albertel 9868: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9869:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9870: #converted
1.599     albertel 9871: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9872:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9873: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9874: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9875: #1.1 only
1.870     albertel 9876: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9877: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9878: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9879: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9880:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9881:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9882:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9883:    &flushcourselogs();
                   9884:    &logthis("Shutting down");
                   9885: }
                   9886: 
1.852     albertel 9887: sub get_dns {
1.869     albertel 9888:     my ($url,$func,$ignore_cache) = @_;
                   9889:     if (!$ignore_cache) {
                   9890: 	my ($content,$cached)=
                   9891: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9892: 	if ($cached) {
                   9893: 	    &$func($content);
                   9894: 	    return;
                   9895: 	}
                   9896:     }
                   9897: 
                   9898:     my %alldns;
1.852     albertel 9899:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9900:     foreach my $dns (<$config>) {
                   9901: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9902:         my $line = $1;
                   9903:         my ($host,$protocol) = split(/:/,$line);
                   9904:         if ($protocol ne 'https') {
                   9905:             $protocol = 'http';
                   9906:         }
                   9907: 	$alldns{$host} = $protocol;
1.869     albertel 9908:     }
                   9909:     while (%alldns) {
                   9910: 	my ($dns) = keys(%alldns);
1.852     albertel 9911: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9912: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9913: 	my $response=$ua->request($request);
1.979     raeburn  9914:         delete($alldns{$dns});
1.852     albertel 9915: 	next if ($response->is_error());
                   9916: 	my @content = split("\n",$response->content);
1.869     albertel 9917: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9918: 	&$func(\@content);
1.869     albertel 9919: 	return;
1.852     albertel 9920:     }
                   9921:     close($config);
1.871     albertel 9922:     my $which = (split('/',$url))[3];
                   9923:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9924:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9925:     my @content = <$config>;
                   9926:     &$func(\@content);
                   9927:     return;
1.852     albertel 9928: }
1.327     albertel 9929: # ------------------------------------------------------------ Read domain file
                   9930: {
1.852     albertel 9931:     my $loaded;
1.846     albertel 9932:     my %domain;
                   9933: 
1.852     albertel 9934:     sub parse_domain_tab {
                   9935: 	my ($lines) = @_;
                   9936: 	foreach my $line (@$lines) {
                   9937: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9938: 
1.846     albertel 9939: 	    chomp($line);
1.852     albertel 9940: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9941: 	    my %this_domain;
                   9942: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9943: 			       'lang_def', 'city', 'longi', 'lati',
                   9944: 			       'primary') {
                   9945: 		$this_domain{$field} = shift(@elements);
                   9946: 	    }
                   9947: 	    $domain{$name} = \%this_domain;
1.852     albertel 9948: 	}
                   9949:     }
1.864     albertel 9950: 
                   9951:     sub reset_domain_info {
                   9952: 	undef($loaded);
                   9953: 	undef(%domain);
                   9954:     }
                   9955: 
1.852     albertel 9956:     sub load_domain_tab {
1.869     albertel 9957: 	my ($ignore_cache) = @_;
                   9958: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9959: 	my $fh;
                   9960: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9961: 	    my @lines = <$fh>;
                   9962: 	    &parse_domain_tab(\@lines);
1.448     albertel 9963: 	}
1.852     albertel 9964: 	close($fh);
                   9965: 	$loaded = 1;
1.327     albertel 9966:     }
1.846     albertel 9967: 
                   9968:     sub domain {
1.852     albertel 9969: 	&load_domain_tab() if (!$loaded);
                   9970: 
1.846     albertel 9971: 	my ($name,$what) = @_;
                   9972: 	return if ( !exists($domain{$name}) );
                   9973: 
                   9974: 	if (!$what) {
                   9975: 	    return $domain{$name}{'description'};
                   9976: 	}
                   9977: 	return $domain{$name}{$what};
                   9978:     }
1.974     raeburn  9979: 
                   9980:     sub domain_info {
                   9981:         &load_domain_tab() if (!$loaded);
                   9982:         return %domain;
                   9983:     }
                   9984: 
1.327     albertel 9985: }
                   9986: 
                   9987: 
1.1       albertel 9988: # ------------------------------------------------------------- Read hosts file
                   9989: {
1.838     albertel 9990:     my %hostname;
1.844     albertel 9991:     my %hostdom;
1.845     albertel 9992:     my %libserv;
1.852     albertel 9993:     my $loaded;
1.888     albertel 9994:     my %name_to_host;
1.1074    raeburn  9995:     my %internetdom;
1.852     albertel 9996: 
                   9997:     sub parse_hosts_tab {
                   9998: 	my ($file) = @_;
                   9999: 	foreach my $configline (@$file) {
                   10000: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10001: 	    next if ($configline =~ /^\^/);
                   10002: 	    chomp($configline);
1.1074    raeburn  10003: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10004: 	    $name=~s/\s//g;
                   10005: 	    if ($id && $domain && $role && $name) {
                   10006: 		$hostname{$id}=$name;
1.888     albertel 10007: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10008: 		$hostdom{$id}=$domain;
                   10009: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10010:                 if (defined($protocol)) {
                   10011:                     if ($protocol eq 'https') {
                   10012:                         $protocol{$id} = $protocol;
                   10013:                     } else {
                   10014:                         $protocol{$id} = 'http'; 
                   10015:                     }
1.968     raeburn  10016:                 } else {
1.969     raeburn  10017:                     $protocol{$id} = 'http';
1.968     raeburn  10018:                 }
1.1074    raeburn  10019:                 if (defined($intdom)) {
                   10020:                     $internetdom{$id} = $intdom;
                   10021:                 }
1.852     albertel 10022: 	    }
                   10023: 	}
                   10024:     }
1.864     albertel 10025:     
                   10026:     sub reset_hosts_info {
1.897     albertel 10027: 	&purge_remembered();
1.864     albertel 10028: 	&reset_domain_info();
                   10029: 	&reset_hosts_ip_info();
1.892     albertel 10030: 	undef(%name_to_host);
1.864     albertel 10031: 	undef(%hostname);
                   10032: 	undef(%hostdom);
                   10033: 	undef(%libserv);
                   10034: 	undef($loaded);
                   10035:     }
1.1       albertel 10036: 
1.852     albertel 10037:     sub load_hosts_tab {
1.869     albertel 10038: 	my ($ignore_cache) = @_;
                   10039: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10040: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10041: 	my @config = <$config>;
                   10042: 	&parse_hosts_tab(\@config);
                   10043: 	close($config);
                   10044: 	$loaded=1;
1.1       albertel 10045:     }
1.852     albertel 10046: 
1.838     albertel 10047:     sub hostname {
1.852     albertel 10048: 	&load_hosts_tab() if (!$loaded);
                   10049: 
1.838     albertel 10050: 	my ($lonid) = @_;
                   10051: 	return $hostname{$lonid};
                   10052:     }
1.845     albertel 10053: 
1.838     albertel 10054:     sub all_hostnames {
1.852     albertel 10055: 	&load_hosts_tab() if (!$loaded);
                   10056: 
1.838     albertel 10057: 	return %hostname;
                   10058:     }
1.845     albertel 10059: 
1.888     albertel 10060:     sub all_names {
                   10061: 	&load_hosts_tab() if (!$loaded);
                   10062: 
                   10063: 	return %name_to_host;
                   10064:     }
                   10065: 
1.974     raeburn  10066:     sub all_host_domain {
                   10067:         &load_hosts_tab() if (!$loaded);
                   10068:         return %hostdom;
                   10069:     }
                   10070: 
1.845     albertel 10071:     sub is_library {
1.852     albertel 10072: 	&load_hosts_tab() if (!$loaded);
                   10073: 
1.845     albertel 10074: 	return exists($libserv{$_[0]});
                   10075:     }
                   10076: 
                   10077:     sub all_library {
1.852     albertel 10078: 	&load_hosts_tab() if (!$loaded);
                   10079: 
1.845     albertel 10080: 	return %libserv;
                   10081:     }
                   10082: 
1.1062    droeschl 10083:     sub unique_library {
                   10084: 	#2x reverse removes all hostnames that appear more than once
                   10085:         my %unique = reverse &all_library();
                   10086:         return reverse %unique;
                   10087:     }
                   10088: 
1.841     albertel 10089:     sub get_servers {
1.852     albertel 10090: 	&load_hosts_tab() if (!$loaded);
                   10091: 
1.841     albertel 10092: 	my ($domain,$type) = @_;
                   10093: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10094: 	                                          : %hostname;
                   10095: 	my %result;
1.842     albertel 10096: 	if (ref($domain) eq 'ARRAY') {
                   10097: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10098: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10099: 		    $result{$host} = $hostname;
                   10100: 		}
                   10101: 	    }
                   10102: 	} else {
                   10103: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10104: 		if ($hostdom{$host} eq $domain) {
                   10105: 		    $result{$host} = $hostname;
                   10106: 		}
1.841     albertel 10107: 	    }
                   10108: 	}
                   10109: 	return %result;
                   10110:     }
1.845     albertel 10111: 
1.1062    droeschl 10112:     sub get_unique_servers {
                   10113:         my %unique = reverse &get_servers(@_);
                   10114: 	return reverse %unique;
                   10115:     }
                   10116: 
1.844     albertel 10117:     sub host_domain {
1.852     albertel 10118: 	&load_hosts_tab() if (!$loaded);
                   10119: 
1.844     albertel 10120: 	my ($lonid) = @_;
                   10121: 	return $hostdom{$lonid};
                   10122:     }
                   10123: 
1.841     albertel 10124:     sub all_domains {
1.852     albertel 10125: 	&load_hosts_tab() if (!$loaded);
                   10126: 
1.841     albertel 10127: 	my %seen;
                   10128: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10129: 	return @uniq;
                   10130:     }
1.1074    raeburn  10131: 
                   10132:     sub internet_dom {
                   10133:         &load_hosts_tab() if (!$loaded);
                   10134: 
                   10135:         my ($lonid) = @_;
                   10136:         return $internetdom{$lonid};
                   10137:     }
1.1       albertel 10138: }
                   10139: 
1.847     albertel 10140: { 
                   10141:     my %iphost;
1.856     albertel 10142:     my %name_to_ip;
                   10143:     my %lonid_to_ip;
1.869     albertel 10144: 
1.847     albertel 10145:     sub get_hosts_from_ip {
                   10146: 	my ($ip) = @_;
                   10147: 	my %iphosts = &get_iphost();
                   10148: 	if (ref($iphosts{$ip})) {
                   10149: 	    return @{$iphosts{$ip}};
                   10150: 	}
                   10151: 	return;
1.839     albertel 10152:     }
1.864     albertel 10153:     
                   10154:     sub reset_hosts_ip_info {
                   10155: 	undef(%iphost);
                   10156: 	undef(%name_to_ip);
                   10157: 	undef(%lonid_to_ip);
                   10158:     }
1.856     albertel 10159: 
                   10160:     sub get_host_ip {
                   10161: 	my ($lonid) = @_;
                   10162: 	if (exists($lonid_to_ip{$lonid})) {
                   10163: 	    return $lonid_to_ip{$lonid};
                   10164: 	}
                   10165: 	my $name=&hostname($lonid);
                   10166:    	my $ip = gethostbyname($name);
                   10167: 	return if (!$ip || length($ip) ne 4);
                   10168: 	$ip=inet_ntoa($ip);
                   10169: 	$name_to_ip{$name}   = $ip;
                   10170: 	$lonid_to_ip{$lonid} = $ip;
                   10171: 	return $ip;
                   10172:     }
1.847     albertel 10173:     
                   10174:     sub get_iphost {
1.869     albertel 10175: 	my ($ignore_cache) = @_;
1.894     albertel 10176: 
1.869     albertel 10177: 	if (!$ignore_cache) {
                   10178: 	    if (%iphost) {
                   10179: 		return %iphost;
                   10180: 	    }
                   10181: 	    my ($ip_info,$cached)=
                   10182: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10183: 	    if ($cached) {
                   10184: 		%iphost      = %{$ip_info->[0]};
                   10185: 		%name_to_ip  = %{$ip_info->[1]};
                   10186: 		%lonid_to_ip = %{$ip_info->[2]};
                   10187: 		return %iphost;
                   10188: 	    }
                   10189: 	}
1.894     albertel 10190: 
                   10191: 	# get yesterday's info for fallback
                   10192: 	my %old_name_to_ip;
                   10193: 	my ($ip_info,$cached)=
                   10194: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10195: 	if ($cached) {
                   10196: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10197: 	}
                   10198: 
1.888     albertel 10199: 	my %name_to_host = &all_names();
                   10200: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10201: 	    my $ip;
                   10202: 	    if (!exists($name_to_ip{$name})) {
                   10203: 		$ip = gethostbyname($name);
                   10204: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10205: 		    if (defined($old_name_to_ip{$name})) {
                   10206: 			$ip = $old_name_to_ip{$name};
                   10207: 			&logthis("Can't find $name defaulting to old $ip");
                   10208: 		    } else {
                   10209: 			&logthis("Name $name no IP found");
                   10210: 			next;
                   10211: 		    }
                   10212: 		} else {
                   10213: 		    $ip=inet_ntoa($ip);
1.847     albertel 10214: 		}
                   10215: 		$name_to_ip{$name} = $ip;
                   10216: 	    } else {
                   10217: 		$ip = $name_to_ip{$name};
1.653     albertel 10218: 	    }
1.888     albertel 10219: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10220: 		$lonid_to_ip{$id} = $ip;
                   10221: 	    }
                   10222: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10223: 	}
1.869     albertel 10224: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10225: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10226: 				      48*60*60);
1.869     albertel 10227: 
1.847     albertel 10228: 	return %iphost;
1.598     albertel 10229:     }
                   10230: 
1.992     raeburn  10231:     #
                   10232:     #  Given a DNS returns the loncapa host name for that DNS 
                   10233:     # 
                   10234:     sub host_from_dns {
                   10235:         my ($dns) = @_;
                   10236:         my @hosts;
                   10237:         my $ip;
                   10238: 
1.993     raeburn  10239:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10240:             $ip = $name_to_ip{$dns};
                   10241:         }
                   10242:         if (!$ip) {
                   10243:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10244:             if (length($ip) == 4) { 
                   10245: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10246:             }
                   10247:         }
                   10248:         if ($ip) {
                   10249: 	    @hosts = get_hosts_from_ip($ip);
                   10250: 	    return $hosts[0];
                   10251:         }
                   10252:         return undef;
1.986     foxr     10253:     }
1.992     raeburn  10254: 
1.1074    raeburn  10255:     sub get_internet_names {
                   10256:         my ($lonid) = @_;
                   10257:         return if ($lonid eq '');
                   10258:         my ($idnref,$cached)=
                   10259:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10260:         if ($cached) {
                   10261:             return $idnref;
                   10262:         }
                   10263:         my $ip = &get_host_ip($lonid);
                   10264:         my @hosts = &get_hosts_from_ip($ip);
                   10265:         my %iphost = &get_iphost();
                   10266:         my (@idns,%seen);
                   10267:         foreach my $id (@hosts) {
                   10268:             my $dom = &host_domain($id);
                   10269:             my $prim_id = &domain($dom,'primary');
                   10270:             my $prim_ip = &get_host_ip($prim_id);
                   10271:             next if ($seen{$prim_ip});
                   10272:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10273:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10274:                     my $intdom = &internet_dom($id);
                   10275:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10276:                         push(@idns,$intdom);
                   10277:                     }
                   10278:                 }
                   10279:             }
                   10280:             $seen{$prim_ip} = 1;
                   10281:         }
                   10282:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10283:     }
                   10284: 
1.986     foxr     10285: }
                   10286: 
1.1079    raeburn  10287: sub all_loncaparevs {
                   10288:     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);
                   10289: }
                   10290: 
1.862     albertel 10291: BEGIN {
                   10292: 
                   10293: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10294:     unless ($readit) {
                   10295: {
                   10296:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10297:     %perlvar = (%perlvar,%{$configvars});
                   10298: }
                   10299: 
                   10300: 
1.1       albertel 10301: # ------------------------------------------------------ Read spare server file
                   10302: {
1.448     albertel 10303:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10304: 
                   10305:     while (my $configline=<$config>) {
                   10306:        chomp($configline);
1.284     matthew  10307:        if ($configline) {
1.784     albertel 10308: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10309: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10310: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10311:        }
                   10312:     }
1.448     albertel 10313:     close($config);
1.1       albertel 10314: }
1.11      www      10315: # ------------------------------------------------------------ Read permissions
                   10316: {
1.448     albertel 10317:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10318: 
                   10319:     while (my $configline=<$config>) {
1.448     albertel 10320: 	chomp($configline);
                   10321: 	if ($configline) {
                   10322: 	    my ($role,$perm)=split(/ /,$configline);
                   10323: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10324: 	}
1.11      www      10325:     }
1.448     albertel 10326:     close($config);
1.11      www      10327: }
                   10328: 
                   10329: # -------------------------------------------- Read plain texts for permissions
                   10330: {
1.448     albertel 10331:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10332: 
                   10333:     while (my $configline=<$config>) {
1.448     albertel 10334: 	chomp($configline);
                   10335: 	if ($configline) {
1.742     raeburn  10336: 	    my ($short,@plain)=split(/:/,$configline);
                   10337:             %{$prp{$short}} = ();
                   10338: 	    if (@plain > 0) {
                   10339:                 $prp{$short}{'std'} = $plain[0];
                   10340:                 for (my $i=1; $i<@plain; $i++) {
                   10341:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10342:                 }
                   10343:             }
1.448     albertel 10344: 	}
1.135     www      10345:     }
1.448     albertel 10346:     close($config);
1.135     www      10347: }
                   10348: 
                   10349: # ---------------------------------------------------------- Read package table
                   10350: {
1.448     albertel 10351:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10352: 
                   10353:     while (my $configline=<$config>) {
1.483     albertel 10354: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10355: 	chomp($configline);
                   10356: 	my ($short,$plain)=split(/:/,$configline);
                   10357: 	my ($pack,$name)=split(/\&/,$short);
                   10358: 	if ($plain ne '') {
                   10359: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10360: 	    $packagetab{$short}=$plain; 
                   10361: 	}
1.11      www      10362:     }
1.448     albertel 10363:     close($config);
1.329     matthew  10364: }
                   10365: 
1.1073    raeburn  10366: # ---------------------------------------------------------- Read loncaparev table
                   10367: {
                   10368:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10369:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10370:             while (my $configline=<$config>) {
                   10371:                 chomp($configline);
                   10372:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10373:                 $loncaparevs{$hostid}=$loncaparev;
                   10374:             }
                   10375:             close($config);
                   10376:         }
                   10377:     }
                   10378: }
                   10379: 
1.1074    raeburn  10380: # ---------------------------------------------------------- Read serverhostID table
                   10381: {
                   10382:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10383:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10384:             while (my $configline=<$config>) {
                   10385:                 chomp($configline);
                   10386:                 my ($name,$id)=split(/:/,$configline);
                   10387:                 $serverhomeIDs{$name}=$id;
                   10388:             }
                   10389:             close($config);
                   10390:         }
                   10391:     }
                   10392: }
                   10393: 
1.1079    raeburn  10394: {
                   10395:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10396:     if (-e $file) {
                   10397:         my $parser = HTML::LCParser->new($file);
                   10398:         while (my $token = $parser->get_token()) {
                   10399:             if ($token->[0] eq 'S') {
                   10400:                 my $item = $token->[1];
                   10401:                 my $name = $token->[2]{'name'};
                   10402:                 my $value = $token->[2]{'value'};
                   10403:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10404:                     my $release = $parser->get_text();
                   10405:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10406:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10407:                 }
                   10408:             }
                   10409:         }
                   10410:     }
1.1073    raeburn  10411: }
                   10412: 
1.329     matthew  10413: # ------------- set up temporary directory
                   10414: {
                   10415:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10416: 
1.11      www      10417: }
                   10418: 
1.794     albertel 10419: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10420: 				'compress_threshold'=> 20_000,
                   10421:  			        });
1.185     www      10422: 
1.281     www      10423: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10424: $dumpcount=0;
1.958     www      10425: $locknum=0;
1.22      www      10426: 
1.163     harris41 10427: &logtouch();
1.672     albertel 10428: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10429: $readit=1;
1.564     albertel 10430:     {
                   10431: 	use integer;
                   10432: 	my $test=(2**32)+1;
1.568     albertel 10433: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10434: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10435:     }
1.195     www      10436: }
1.1       albertel 10437: }
1.179     www      10438: 
1.1       albertel 10439: 1;
1.191     harris41 10440: __END__
                   10441: 
1.243     albertel 10442: =pod
                   10443: 
1.191     harris41 10444: =head1 NAME
                   10445: 
1.243     albertel 10446: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10447: 
                   10448: =head1 SYNOPSIS
                   10449: 
1.243     albertel 10450: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10451: 
                   10452:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10453: 
1.243     albertel 10454: Common parameters:
                   10455: 
                   10456: =over 4
                   10457: 
                   10458: =item *
                   10459: 
                   10460: $uname : an internal username (if $cname expecting a course Id specifically)
                   10461: 
                   10462: =item *
                   10463: 
                   10464: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10465: 
                   10466: =item *
                   10467: 
                   10468: $symb : a resource instance identifier
                   10469: 
                   10470: =item *
                   10471: 
                   10472: $namespace : the name of a .db file that contains the data needed or
                   10473: being set.
                   10474: 
                   10475: =back
                   10476: 
1.394     bowersj2 10477: =head1 OVERVIEW
1.191     harris41 10478: 
1.394     bowersj2 10479: lonnet provides subroutines which interact with the
                   10480: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10481: about classes, users, and resources.
1.243     albertel 10482: 
                   10483: For many of these objects you can also use this to store data about
                   10484: them or modify them in various ways.
1.191     harris41 10485: 
1.394     bowersj2 10486: =head2 Symbs
1.191     harris41 10487: 
1.394     bowersj2 10488: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10489: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10490: map, the resource number of the resource in the map, and the URL of
                   10491: the resource itself. The latter is somewhat redundant, but might help
                   10492: if maps change.
                   10493: 
                   10494: An example is
                   10495: 
                   10496:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10497: 
                   10498: The respective map entry is
                   10499: 
                   10500:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10501:   title="Problem 2">
                   10502:  </resource>
                   10503: 
                   10504: Symbs are used by the random number generator, as well as to store and
                   10505: restore data specific to a certain instance of for example a problem.
                   10506: 
                   10507: =head2 Storing And Retrieving Data
                   10508: 
                   10509: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10510: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10511: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10512: is is the non-critical message twin of cstore. These functions are for
                   10513: handlers to store a perl hash to a user's permanent data space in an
                   10514: easy manner, and to retrieve it again on another call. It is expected
                   10515: that a handler would use this once at the beginning to retrieve data,
                   10516: and then again once at the end to send only the new data back.
                   10517: 
                   10518: The data is stored in the user's data directory on the user's
                   10519: homeserver under the ID of the course.
                   10520: 
                   10521: The hash that is returned by restore will have all of the previous
                   10522: value for all of the elements of the hash.
                   10523: 
                   10524: Example:
                   10525: 
                   10526:  #creating a hash
                   10527:  my %hash;
                   10528:  $hash{'foo'}='bar';
                   10529: 
                   10530:  #storing it
                   10531:  &Apache::lonnet::cstore(\%hash);
                   10532: 
                   10533:  #changing a value
                   10534:  $hash{'foo'}='notbar';
                   10535: 
                   10536:  #adding a new value
                   10537:  $hash{'bar'}='foo';
                   10538:  &Apache::lonnet::cstore(\%hash);
                   10539: 
                   10540:  #retrieving the hash
                   10541:  my %history=&Apache::lonnet::restore();
                   10542: 
                   10543:  #print the hash
                   10544:  foreach my $key (sort(keys(%history))) {
                   10545:    print("\%history{$key} = $history{$key}");
                   10546:  }
                   10547: 
                   10548: Will print out:
1.191     harris41 10549: 
1.394     bowersj2 10550:  %history{1:foo} = bar
                   10551:  %history{1:keys} = foo:timestamp
                   10552:  %history{1:timestamp} = 990455579
                   10553:  %history{2:bar} = foo
                   10554:  %history{2:foo} = notbar
                   10555:  %history{2:keys} = foo:bar:timestamp
                   10556:  %history{2:timestamp} = 990455580
                   10557:  %history{bar} = foo
                   10558:  %history{foo} = notbar
                   10559:  %history{timestamp} = 990455580
                   10560:  %history{version} = 2
                   10561: 
                   10562: Note that the special hash entries C<keys>, C<version> and
                   10563: C<timestamp> were added to the hash. C<version> will be equal to the
                   10564: total number of versions of the data that have been stored. The
                   10565: C<timestamp> attribute will be the UNIX time the hash was
                   10566: stored. C<keys> is available in every historical section to list which
                   10567: keys were added or changed at a specific historical revision of a
                   10568: hash.
                   10569: 
                   10570: B<Warning>: do not store the hash that restore returns directly. This
                   10571: will cause a mess since it will restore the historical keys as if the
                   10572: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10573: 
1.394     bowersj2 10574: Calling convention:
1.191     harris41 10575: 
1.394     bowersj2 10576:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10577:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10578: 
1.394     bowersj2 10579: For more detailed information, see lonnet specific documentation.
1.191     harris41 10580: 
1.394     bowersj2 10581: =head1 RETURN MESSAGES
1.191     harris41 10582: 
1.394     bowersj2 10583: =over 4
1.191     harris41 10584: 
1.394     bowersj2 10585: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10586: 
1.394     bowersj2 10587: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10588: when the connection is brought back up
1.191     harris41 10589: 
1.394     bowersj2 10590: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10591: for later delivery
1.191     harris41 10592: 
1.967     bisitz   10593: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10594: 
1.394     bowersj2 10595: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10596: that was requested
1.191     harris41 10597: 
1.243     albertel 10598: =back
1.191     harris41 10599: 
1.243     albertel 10600: =head1 PUBLIC SUBROUTINES
1.191     harris41 10601: 
1.243     albertel 10602: =head2 Session Environment Functions
1.191     harris41 10603: 
1.243     albertel 10604: =over 4
1.191     harris41 10605: 
1.394     bowersj2 10606: =item * 
                   10607: X<appenv()>
1.949     raeburn  10608: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10609: the user envirnoment file, and will be restored for each access this
1.620     albertel 10610: user makes during this session, also modifies the %env for the current
1.949     raeburn  10611: process. Optional rolesarrayref - if defined contains a reference to an array
                   10612: of roles which are exempt from the restriction on modifying user.role entries 
                   10613: in the user's environment.db and in %env.    
1.191     harris41 10614: 
                   10615: =item *
1.394     bowersj2 10616: X<delenv()>
1.987     raeburn  10617: B<delenv($delthis,$regexp)>: removes all items from the session
                   10618: environment file that begin with $delthis. If the 
                   10619: optional second arg - $regexp - is true, $delthis is treated as a 
                   10620: regular expression, otherwise \Q$delthis\E is used. 
                   10621: The values are also deleted from the current processes %env.
1.191     harris41 10622: 
1.795     albertel 10623: =item * get_env_multiple($name) 
                   10624: 
                   10625: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10626: values may be defined and end up as an array ref.
                   10627: 
                   10628: returns an array of values
                   10629: 
1.243     albertel 10630: =back
                   10631: 
                   10632: =head2 User Information
1.191     harris41 10633: 
1.243     albertel 10634: =over 4
1.191     harris41 10635: 
                   10636: =item *
1.394     bowersj2 10637: X<queryauthenticate()>
                   10638: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10639: authentication scheme
                   10640: 
                   10641: =item *
1.394     bowersj2 10642: X<authenticate()>
1.1073    raeburn  10643: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10644: authenticate user from domain's lib servers (first use the current
                   10645: one). C<$upass> should be the users password.
1.1073    raeburn  10646: $checkdefauth is optional (value is 1 if a check should be made to
                   10647:    authenticate user using default authentication method, and allow
                   10648:    account creation if username does not have account in the domain).
                   10649: $clientcancheckhost is optional (value is 1 if checking whether the
                   10650:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10651: 
                   10652: =item *
1.394     bowersj2 10653: X<homeserver()>
                   10654: B<homeserver($uname,$udom)>: find the server which has
                   10655: the user's directory and files (there must be only one), this caches
                   10656: the answer, and also caches if there is a borken connection.
1.191     harris41 10657: 
                   10658: =item *
1.394     bowersj2 10659: X<idget()>
                   10660: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10661: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10662: username, and only 1 username per ID in a specific domain) (returns
                   10663: hash: id=>name,id=>name)
1.191     harris41 10664: 
                   10665: =item *
1.394     bowersj2 10666: X<idrget()>
                   10667: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10668: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10669: 
                   10670: =item *
1.394     bowersj2 10671: X<idput()>
                   10672: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10673: 
                   10674: =item *
1.394     bowersj2 10675: X<rolesinit()>
                   10676: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10677: 
                   10678: =item *
1.551     albertel 10679: X<getsection()>
                   10680: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10681: course $cname, return section name/number or '' for "not in course"
                   10682: and '-1' for "no section"
                   10683: 
                   10684: =item *
1.394     bowersj2 10685: X<userenvironment()>
                   10686: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10687: passed in @what from the requested user's environment, returns a hash
                   10688: 
1.858     raeburn  10689: =item * 
                   10690: X<userlog_query()>
1.859     albertel 10691: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10692: activity.log file. %filters defines filters applied when parsing the
                   10693: log file. These can be start or end timestamps, or the type of action
                   10694: - log to look for Login or Logout events, check for Checkin or
                   10695: Checkout, role for role selection. The response is in the form
                   10696: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10697: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10698: 
1.243     albertel 10699: =back
                   10700: 
                   10701: =head2 User Roles
                   10702: 
                   10703: =over 4
                   10704: 
                   10705: =item *
                   10706: 
1.810     raeburn  10707: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10708:  F: full access
                   10709:  U,I,K: authentication modes (cxx only)
                   10710:  '': forbidden
                   10711:  1: user needs to choose course
                   10712:  2: browse allowed
1.766     albertel 10713:  A: passphrase authentication needed
1.243     albertel 10714: 
                   10715: =item *
                   10716: 
                   10717: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10718: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10719: and course level
                   10720: 
                   10721: =item *
                   10722: 
1.988     raeburn  10723: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10724: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10725: $type is Course (default) or Community.
1.988     raeburn  10726: If $forcedefault evaluates to true, text returned will be default 
                   10727: text for $type. Otherwise, if this is a course, the text returned 
                   10728: will be a custom name for the role (if defined in the course's 
                   10729: environment).  If no custom name is defined the default is returned.
                   10730:    
1.832     raeburn  10731: =item *
                   10732: 
1.935     raeburn  10733: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10734: All arguments are optional. Returns a hash of a roles, either for
                   10735: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10736: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10737: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10738: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10739: For each key, value is set to colon-separated start and end times for
                   10740: the role.  If no username and domain are specified, will default to
1.934     raeburn  10741: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10742: of role statuses (active, future or previous), roles 
                   10743: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10744: to restrict the list of roles reported. If no array ref is 
                   10745: provided for types, will default to return only active roles.
1.834     albertel 10746: 
1.243     albertel 10747: =back
                   10748: 
                   10749: =head2 User Modification
                   10750: 
                   10751: =over 4
                   10752: 
                   10753: =item *
                   10754: 
1.957     raeburn  10755: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10756: user for the level given by URL.  Optional start and end dates (leave empty
                   10757: string or zero for "no date")
1.191     harris41 10758: 
                   10759: =item *
                   10760: 
1.243     albertel 10761: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10762: change a users, password, possible return values are: ok,
                   10763: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10764: refused
1.191     harris41 10765: 
                   10766: =item *
                   10767: 
1.243     albertel 10768: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10769: 
                   10770: =item *
                   10771: 
1.1058    raeburn  10772: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10773:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10774: 
                   10775: will update user information (firstname,middlename,lastname,generation,
                   10776: permanentemail), and if forceid is true, student/employee ID also.
                   10777: A user's institutional affiliation(s) can also be updated.
                   10778: User information fields will not be overwritten with empty entries 
                   10779: unless the field is included in the $candelete array reference.
                   10780: This array is included when a single user is modified via "Manage Users",
                   10781: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10782: 
                   10783: =item *
                   10784: 
1.286     matthew  10785: modifystudent
                   10786: 
1.957     raeburn  10787: modify a student's enrollment and identification information.
1.286     matthew  10788: The course id is resolved based on the current users environment.  
                   10789: This means the envoking user must be a course coordinator or otherwise
                   10790: associated with a course.
                   10791: 
1.297     matthew  10792: This call is essentially a wrapper for lonnet::modifyuser and
                   10793: lonnet::modify_student_enrollment
1.286     matthew  10794: 
                   10795: Inputs: 
                   10796: 
                   10797: =over 4
                   10798: 
1.957     raeburn  10799: =item B<$udom> Student's loncapa domain
1.286     matthew  10800: 
1.957     raeburn  10801: =item B<$uname> Student's loncapa login name
1.286     matthew  10802: 
1.964     bisitz   10803: =item B<$uid> Student/Employee ID
1.286     matthew  10804: 
1.957     raeburn  10805: =item B<$umode> Student's authentication mode
1.286     matthew  10806: 
1.957     raeburn  10807: =item B<$upass> Student's password
1.286     matthew  10808: 
1.957     raeburn  10809: =item B<$first> Student's first name
1.286     matthew  10810: 
1.957     raeburn  10811: =item B<$middle> Student's middle name
1.286     matthew  10812: 
1.957     raeburn  10813: =item B<$last> Student's last name
1.286     matthew  10814: 
1.957     raeburn  10815: =item B<$gene> Student's generation
1.286     matthew  10816: 
1.957     raeburn  10817: =item B<$usec> Student's section in course
1.286     matthew  10818: 
                   10819: =item B<$end> Unix time of the roles expiration
                   10820: 
                   10821: =item B<$start> Unix time of the roles start date
                   10822: 
                   10823: =item B<$forceid> If defined, allow $uid to be changed
                   10824: 
                   10825: =item B<$desiredhome> server to use as home server for student
                   10826: 
1.957     raeburn  10827: =item B<$email> Student's permanent e-mail address
                   10828: 
                   10829: =item B<$type> Type of enrollment (auto or manual)
                   10830: 
1.963     raeburn  10831: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10832: 
                   10833: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10834: 
1.963     raeburn  10835: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10836: 
1.963     raeburn  10837: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10838: 
1.963     raeburn  10839: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10840: 
1.286     matthew  10841: =back
1.297     matthew  10842: 
                   10843: =item *
                   10844: 
                   10845: modify_student_enrollment
                   10846: 
                   10847: Change a students enrollment status in a class.  The environment variable
                   10848: 'role.request.course' must be defined for this function to proceed.
                   10849: 
                   10850: Inputs:
                   10851: 
                   10852: =over 4
                   10853: 
                   10854: =item $udom, students domain
                   10855: 
                   10856: =item $uname, students name
                   10857: 
                   10858: =item $uid, students user id
                   10859: 
                   10860: =item $first, students first name
                   10861: 
                   10862: =item $middle
                   10863: 
                   10864: =item $last
                   10865: 
                   10866: =item $gene
                   10867: 
                   10868: =item $usec
                   10869: 
                   10870: =item $end
                   10871: 
                   10872: =item $start
                   10873: 
1.957     raeburn  10874: =item $type
                   10875: 
                   10876: =item $locktype
                   10877: 
                   10878: =item $cid
                   10879: 
                   10880: =item $selfenroll
                   10881: 
                   10882: =item $context
                   10883: 
1.297     matthew  10884: =back
                   10885: 
1.191     harris41 10886: 
                   10887: =item *
                   10888: 
1.243     albertel 10889: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10890: custom role; give a custom role to a user for the level given by URL.  Specify
                   10891: name and domain of role author, and role name
1.191     harris41 10892: 
                   10893: =item *
                   10894: 
1.243     albertel 10895: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10896: 
                   10897: =item *
                   10898: 
1.243     albertel 10899: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10900: 
                   10901: =back
                   10902: 
                   10903: =head2 Course Infomation
                   10904: 
                   10905: =over 4
1.191     harris41 10906: 
                   10907: =item *
                   10908: 
1.631     albertel 10909: coursedescription($courseid) : returns a hash of information about the
                   10910: specified course id, including all environment settings for the
                   10911: course, the description of the course will be in the hash under the
                   10912: key 'description'
1.191     harris41 10913: 
                   10914: =item *
                   10915: 
1.624     albertel 10916: resdata($name,$domain,$type,@which) : request for current parameter
                   10917: setting for a specific $type, where $type is either 'course' or 'user',
                   10918: @what should be a list of parameters to ask about. This routine caches
                   10919: answers for 5 minutes.
1.243     albertel 10920: 
1.877     foxr     10921: =item *
                   10922: 
                   10923: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10924: data base, returning a hash that is keyed by the resource name and has
                   10925: values that are the resource value.  I believe that the timestamps and
                   10926: versions are also returned.
                   10927: 
                   10928: 
1.243     albertel 10929: =back
                   10930: 
                   10931: =head2 Course Modification
                   10932: 
                   10933: =over 4
1.191     harris41 10934: 
                   10935: =item *
                   10936: 
1.243     albertel 10937: writecoursepref($courseid,%prefs) : write preferences (environment
                   10938: database) for a course
1.191     harris41 10939: 
                   10940: =item *
                   10941: 
1.1011    raeburn  10942: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10943: 
                   10944: =item *
                   10945: 
1.1038    raeburn  10946: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10947: 
                   10948: =back
                   10949: 
                   10950: =head2 Resource Subroutines
                   10951: 
                   10952: =over 4
1.191     harris41 10953: 
                   10954: =item *
                   10955: 
1.243     albertel 10956: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10957: 
                   10958: =item *
                   10959: 
1.243     albertel 10960: repcopy($filename) : subscribes to the requested file, and attempts to
                   10961: replicate from the owning library server, Might return
1.607     raeburn  10962: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10963: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10964: resource. Expects the local filesystem pathname
                   10965: (/home/httpd/html/res/....)
                   10966: 
                   10967: =back
                   10968: 
                   10969: =head2 Resource Information
                   10970: 
                   10971: =over 4
1.191     harris41 10972: 
                   10973: =item *
                   10974: 
1.243     albertel 10975: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10976: a vairety of different possible values, $varname should be a request
                   10977: string, and the other parameters can be used to specify who and what
                   10978: one is asking about.
                   10979: 
                   10980: Possible values for $varname are environment.lastname (or other item
                   10981: from the envirnment hash), user.name (or someother aspect about the
                   10982: user), resource.0.maxtries (or some other part and parameter of a
                   10983: resource)
1.204     albertel 10984: 
                   10985: =item *
                   10986: 
1.243     albertel 10987: directcondval($number) : get current value of a condition; reads from a state
                   10988: string
1.204     albertel 10989: 
                   10990: =item *
                   10991: 
1.243     albertel 10992: condval($condidx) : value of condition index based on state
1.204     albertel 10993: 
                   10994: =item *
                   10995: 
1.243     albertel 10996: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10997: resource's metadata, $what should be either a specific key, or either
                   10998: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10999: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11000: 
                   11001: this function automatically caches all requests
1.191     harris41 11002: 
                   11003: =item *
                   11004: 
1.243     albertel 11005: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11006: network of library servers; returns file handle of where SQL and regex results
                   11007: will be stored for query
1.191     harris41 11008: 
                   11009: =item *
                   11010: 
1.243     albertel 11011: symbread($filename) : return symbolic list entry (filename argument optional);
                   11012: returns the data handle
1.191     harris41 11013: 
                   11014: =item *
                   11015: 
1.243     albertel 11016: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11017: a possible symb for the URL in $thisfn, and if is an encryypted
                   11018: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11019: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11020: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11021: 
1.191     harris41 11022: 
                   11023: =item *
                   11024: 
1.243     albertel 11025: symbclean($symb) : removes versions numbers from a symb, returns the
                   11026: cleaned symb
1.191     harris41 11027: 
                   11028: =item *
                   11029: 
1.243     albertel 11030: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11031: course map, user must be in a course for it to work.
1.191     harris41 11032: 
                   11033: =item *
                   11034: 
1.243     albertel 11035: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11036: 
                   11037: =item *
                   11038: 
1.243     albertel 11039: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11040: a random seed, all arguments are optional, if they aren't sent it uses the
                   11041: environment to derive them. Note: if symb isn't sent and it can't get one
                   11042: from &symbread it will use the current time as its return value
1.191     harris41 11043: 
                   11044: =item *
                   11045: 
1.243     albertel 11046: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11047: unfakeable, receipt
1.191     harris41 11048: 
                   11049: =item *
                   11050: 
1.620     albertel 11051: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11052: 
                   11053: =item *
                   11054: 
1.243     albertel 11055: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11056: 
                   11057: =item *
                   11058: 
1.243     albertel 11059: 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 11060: 
                   11061: =item *
                   11062: 
1.243     albertel 11063: 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 11064: 
                   11065: =item *
                   11066: 
1.243     albertel 11067: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11068: 
                   11069: =item *
                   11070: 
1.243     albertel 11071: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11072: forcing spreadsheet to reevaluate the resource scores next time.
                   11073: 
                   11074: =back
                   11075: 
                   11076: =head2 Storing/Retreiving Data
                   11077: 
                   11078: =over 4
1.191     harris41 11079: 
                   11080: =item *
                   11081: 
1.243     albertel 11082: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11083: for this url; hashref needs to be given and should be a \%hashname; the
                   11084: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11085: be derived from the env
1.191     harris41 11086: 
                   11087: =item *
                   11088: 
1.243     albertel 11089: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11090: uses critical subroutine
1.191     harris41 11091: 
                   11092: =item *
                   11093: 
1.243     albertel 11094: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11095: all args are optional
1.191     harris41 11096: 
                   11097: =item *
                   11098: 
1.717     albertel 11099: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11100: dumps the complete (or key matching regexp) namespace into a hash
                   11101: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11102: normally &store()ed into
                   11103: 
                   11104: $range should be either an integer '100' (give me the first 100
                   11105:                                            matching records)
                   11106:               or be  two integers sperated by a - with no spaces
                   11107:                  '30-50' (give me the 30th through the 50th matching
                   11108:                           records)
                   11109: 
                   11110: 
                   11111: =item *
                   11112: 
                   11113: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11114: replaces a &store() version of data with a replacement set of data
                   11115: for a particular resource in a namespace passed in the $storehash hash 
                   11116: reference
                   11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11121: works very similar to store/cstore, but all data is stored in a
                   11122: temporary location and can be reset using tmpreset, $storehash should
                   11123: be a hash reference, returns nothing on success
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11128: similar to restore, but all data is stored in a temporary location and
                   11129: can be reset using tmpreset. Returns a hash of values on success,
                   11130: error string otherwise.
1.191     harris41 11131: 
                   11132: =item *
                   11133: 
1.243     albertel 11134: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11135: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11140: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11141: 
                   11142: =item *
                   11143: 
1.243     albertel 11144: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11145: namesp ($udom and $uname are optional)
1.191     harris41 11146: 
                   11147: =item *
                   11148: 
1.702     albertel 11149: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11150: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11151: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11152: 
1.702     albertel 11153: $range should be either an integer '100' (give me the first 100
                   11154:                                            matching records)
                   11155:               or be  two integers sperated by a - with no spaces
                   11156:                  '30-50' (give me the 30th through the 50th matching
                   11157:                           records)
1.449     matthew  11158: =item *
                   11159: 
                   11160: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11161: $store can be a scalar, an array reference, or if the amount to be 
                   11162: incremented is > 1, a hash reference.
                   11163: 
                   11164: ($udom and $uname are optional)
1.191     harris41 11165: 
                   11166: =item *
                   11167: 
1.243     albertel 11168: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11169: ($udom and $uname are optional)
1.191     harris41 11170: 
                   11171: =item *
                   11172: 
1.243     albertel 11173: cput($namespace,$storehash,$udom,$uname) : critical put
                   11174: ($udom and $uname are optional)
1.191     harris41 11175: 
                   11176: =item *
                   11177: 
1.748     albertel 11178: newput($namespace,$storehash,$udom,$uname) :
                   11179: 
                   11180: Attempts to store the items in the $storehash, but only if they don't
                   11181: currently exist, if this succeeds you can be certain that you have 
                   11182: successfully created a new key value pair in the $namespace db.
                   11183: 
                   11184: 
                   11185: Args:
                   11186:  $namespace: name of database to store values to
                   11187:  $storehash: hashref to store to the db
                   11188:  $udom: (optional) domain of user containing the db
                   11189:  $uname: (optional) name of user caontaining the db
                   11190: 
                   11191: Returns:
                   11192:  'ok' -> succeeded in storing all keys of $storehash
                   11193:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11194:                         least <key> already existed in the db (other
                   11195:                         requested keys may also already exist)
1.967     bisitz   11196:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11197:  'con_lost' -> unable to contact request server
                   11198:  'refused' -> action was not allowed by remote machine
                   11199: 
                   11200: 
                   11201: =item *
                   11202: 
1.243     albertel 11203: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11204: reference filled in from namesp (encrypts the return communication)
                   11205: ($udom and $uname are optional)
1.191     harris41 11206: 
                   11207: =item *
                   11208: 
1.243     albertel 11209: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11210: critical subroutine
                   11211: 
1.806     raeburn  11212: =item *
                   11213: 
1.860     raeburn  11214: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11215: array reference filled in from namespace found in domain level on either
                   11216: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11217: 
                   11218: =item *
                   11219: 
1.860     raeburn  11220: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11221: domain level either on specified domain server ($uhome) or primary domain 
                   11222: server ($udom and $uhome are optional)
1.806     raeburn  11223: 
1.943     raeburn  11224: =item * 
                   11225: 
                   11226: get_domain_defaults($target_domain) : returns hash with defaults for
                   11227: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11228: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11229: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11230: Values are retrieved from cache (if current), or from domain's configuration.db
                   11231: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11232: or lonTabs/domain.tab. 
                   11233: 
                   11234: %domdefaults = &get_auth_defaults($target_domain);
                   11235: 
1.243     albertel 11236: =back
                   11237: 
                   11238: =head2 Network Status Functions
                   11239: 
                   11240: =over 4
1.191     harris41 11241: 
                   11242: =item *
                   11243: 
                   11244: dirlist($uri) : return directory list based on URI
                   11245: 
                   11246: =item *
                   11247: 
1.243     albertel 11248: spareserver() : find server with least workload from spare.tab
                   11249: 
1.986     foxr     11250: 
                   11251: =item *
                   11252: 
                   11253: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11254: if there is no corresponding loncapa host.
                   11255: 
1.243     albertel 11256: =back
                   11257: 
1.986     foxr     11258: 
1.243     albertel 11259: =head2 Apache Request
                   11260: 
                   11261: =over 4
1.191     harris41 11262: 
                   11263: =item *
                   11264: 
1.243     albertel 11265: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11266: localhost, posts hash
                   11267: 
                   11268: =back
                   11269: 
                   11270: =head2 Data to String to Data
                   11271: 
                   11272: =over 4
1.191     harris41 11273: 
                   11274: =item *
                   11275: 
1.243     albertel 11276: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11277: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11278: 
                   11279: =item *
                   11280: 
1.243     albertel 11281: hashref2str($hashref) : convert a hashref into a string complete with
                   11282: escaping and '=' and '&' separators, supports elements that are
                   11283: arrayrefs and hashrefs
1.191     harris41 11284: 
                   11285: =item *
                   11286: 
1.243     albertel 11287: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11288: with escaping and '&' separators, supports elements that are arrayrefs
                   11289: and hashrefs
1.191     harris41 11290: 
                   11291: =item *
                   11292: 
1.243     albertel 11293: str2hash($string) : convert string to hash using unescaping and
                   11294: splitting on '=' and '&', supports elements that are arrayrefs and
                   11295: hashrefs
1.191     harris41 11296: 
                   11297: =item *
                   11298: 
1.243     albertel 11299: str2array($string) : convert string to hash using unescaping and
                   11300: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11301: 
                   11302: =back
                   11303: 
                   11304: =head2 Logging Routines
                   11305: 
                   11306: =over 4
                   11307: 
                   11308: These routines allow one to make log messages in the lonnet.log and
                   11309: lonnet.perm logfiles.
1.191     harris41 11310: 
                   11311: =item *
                   11312: 
1.243     albertel 11313: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11314: 
                   11315: =item *
                   11316: 
1.243     albertel 11317: logthis() : append message to the normal lonnet.log file, it gets
                   11318: preiodically rolled over and deleted.
1.191     harris41 11319: 
                   11320: =item *
                   11321: 
1.243     albertel 11322: logperm() : append a permanent message to lonnet.perm.log, this log
                   11323: file never gets deleted by any automated portion of the system, only
                   11324: messages of critical importance should go in here.
                   11325: 
                   11326: =back
                   11327: 
                   11328: =head2 General File Helper Routines
                   11329: 
                   11330: =over 4
1.191     harris41 11331: 
                   11332: =item *
                   11333: 
1.481     raeburn  11334: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11335: (a) files in /uploaded
                   11336:   (i) If a local copy of the file exists - 
                   11337:       compares modification date of local copy with last-modified date for 
                   11338:       definitive version stored on home server for course. If local copy is 
                   11339:       stale, requests a new version from the home server and stores it. 
                   11340:       If the original has been removed from the home server, then local copy 
                   11341:       is unlinked.
                   11342:   (ii) If local copy does not exist -
                   11343:       requests the file from the home server and stores it. 
                   11344:   
                   11345:   If $caller is 'uploadrep':  
                   11346:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11347:     for request for files originally uploaded via DOCS. 
                   11348:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11349:   
                   11350:   Otherwise:
                   11351:      This indicates a call from the content generation phase of the request.
                   11352:      -  returns the entire contents of the file or -1.
                   11353:      
                   11354: (b) files in /res
                   11355:    - returns the entire contents of a file or -1; 
                   11356:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11357: 
1.712     albertel 11358: 
                   11359: =item *
                   11360: 
                   11361: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11362:                   reference
                   11363: 
                   11364: returns either a stat() list of data about the file or an empty list
                   11365: if the file doesn't exist or couldn't find out about it (connection
                   11366: problems or user unknown)
                   11367: 
1.191     harris41 11368: =item *
                   11369: 
1.243     albertel 11370: filelocation($dir,$file) : returns file system location of a file
                   11371: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11372: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11373: and a file of ../bob will become /a/bob)
1.191     harris41 11374: 
                   11375: =item *
                   11376: 
                   11377: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11378: filelocation except for hrefs
                   11379: 
                   11380: =item *
                   11381: 
                   11382: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11383: 
1.243     albertel 11384: =back
                   11385: 
1.608     albertel 11386: =head2 Usererfile file routines (/uploaded*)
                   11387: 
                   11388: =over 4
                   11389: 
                   11390: =item *
                   11391: 
                   11392: userfileupload(): main rotine for putting a file in a user or course's
                   11393:                   filespace, arguments are,
                   11394: 
1.620     albertel 11395:  formname - required - this is the name of the element in $env where the
1.608     albertel 11396:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11397:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11398:            contents of the file is located in $env{'form.'.$formname}
1.1090  ! raeburn  11399:  context - if coursedoc, store the file in the course of the active role
        !          11400:              of the current user; 
        !          11401:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
        !          11402:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11403:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11404:          if undefined, it will be placed in "unknown"
                   11405: 
                   11406:  (This routine calls clean_filename() to remove any dangerous
                   11407:  characters from the filename, and then calls finuserfileupload() to
                   11408:  complete the transaction)
                   11409: 
                   11410:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11411:  and /adm/notfound.html if unsuccessful
                   11412: 
                   11413: =item *
                   11414: 
                   11415: clean_filename(): routine for cleaing a filename up for storage in
                   11416:                  userfile space, argument is:
                   11417: 
                   11418:  filename - proposed filename
                   11419: 
                   11420: returns: the new clean filename
                   11421: 
                   11422: =item *
                   11423: 
1.1090  ! raeburn  11424: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11425: userspace, probably shouldn't be called directly
                   11426: 
                   11427:   docuname: username or courseid of destination for the file
                   11428:   docudom: domain of user/course of destination for the file
                   11429:   formname: same as for userfileupload()
1.1090  ! raeburn  11430:   fname: filename (including subdirectories) for the file
        !          11431:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
        !          11432:   allfiles: reference to hash used to store objects found by parser
        !          11433:   codebase: reference to hash used for codebases of java objects found by parser
        !          11434:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
        !          11435:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
        !          11436:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
        !          11437:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
        !          11438:   context: if 'overwrite', will move the uploaded file from its temporary location to
        !          11439:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.608     albertel 11440: 
                   11441:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090  ! raeburn  11442:  and /adm/notfound.html if unsuccessful (or an error message if context 
        !          11443:  was 'overwrite').
        !          11444:  
1.608     albertel 11445: 
                   11446: =item *
                   11447: 
                   11448: renameuserfile(): renames an existing userfile to a new name
                   11449: 
                   11450:   Args:
                   11451:    docuname: username or courseid of destination for the file
                   11452:    docudom: domain of user/course of destination for the file
                   11453:    old: current file name (including any subdirs under userfiles)
                   11454:    new: desired file name (including any subdirs under userfiles)
                   11455: 
                   11456: =item *
                   11457: 
                   11458: mkdiruserfile(): creates a directory is a userfiles dir
                   11459: 
                   11460:   Args:
                   11461:    docuname: username or courseid of destination for the file
                   11462:    docudom: domain of user/course of destination for the file
                   11463:    dir: dir to create (including any subdirs under userfiles)
                   11464: 
                   11465: =item *
                   11466: 
                   11467: removeuserfile(): removes a file that exists in userfiles
                   11468: 
                   11469:   Args:
                   11470:    docuname: username or courseid of destination for the file
                   11471:    docudom: domain of user/course of destination for the file
                   11472:    fname: filname to delete (including any subdirs under userfiles)
                   11473: 
                   11474: =item *
                   11475: 
                   11476: removeuploadedurl(): convience function for removeuserfile()
                   11477: 
                   11478:   Args:
                   11479:    url:  a full /uploaded/... url to delete
                   11480: 
1.747     albertel 11481: =item * 
                   11482: 
                   11483: get_portfile_permissions():
                   11484:   Args:
                   11485:     domain: domain of user or course contain the portfolio files
                   11486:     user: name of user or num of course contain the portfolio files
                   11487:   Returns:
                   11488:     hashref of a dump of the proper file_permissions.db
                   11489:    
                   11490: 
                   11491: =item * 
                   11492: 
                   11493: get_access_controls():
                   11494: 
                   11495: Args:
                   11496:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11497:   group: (optional) the group you want the files associated with
                   11498:   file: (optional) the file you want access info on
                   11499: 
                   11500: Returns:
1.749     raeburn  11501:     a hash (keys are file names) of hashes containing
                   11502:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11503:         values are XML containing access control settings (see below) 
1.747     albertel 11504: 
                   11505: Internal notes:
                   11506: 
1.749     raeburn  11507:  access controls are stored in file_permissions.db as key=value pairs.
                   11508:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11509:         where scope -> public,guest,course,group,domains or users.
                   11510:               end -> UNIX time for end of access (0 -> no end date)
                   11511:               start -> UNIX time for start of access
                   11512: 
                   11513:     value -> XML description of access control
                   11514:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11515:             <start></start>
                   11516:             <end></end>
                   11517: 
                   11518:             <password></password>  for scope type = guest
                   11519: 
                   11520:             <domain></domain>     for scope type = course or group
                   11521:             <number></number>
                   11522:             <roles id="">
                   11523:              <role></role>
                   11524:              <access></access>
                   11525:              <section></section>
                   11526:              <group></group>
                   11527:             </roles>
                   11528: 
                   11529:             <dom></dom>         for scope type = domains
                   11530: 
                   11531:             <users>             for scope type = users
                   11532:              <user>
                   11533:               <uname></uname>
                   11534:               <udom></udom>
                   11535:              </user>
                   11536:             </users>
                   11537:            </scope> 
                   11538:               
                   11539:  Access data is also aggregated for each file in an additional key=value pair:
                   11540:  key -> path to file/file_name\0accesscontrol 
                   11541:  value -> reference to hash
                   11542:           hash contains key = value pairs
                   11543:           where key = uniqueID:scope_end_start
                   11544:                 value = UNIX time record was last updated
                   11545: 
                   11546:           Used to improve speed of look-ups of access controls for each file.  
                   11547:  
                   11548:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11549: 
                   11550: modify_access_controls():
                   11551: 
                   11552: Modifies access controls for a portfolio file
                   11553: Args
                   11554: 1. file name
                   11555: 2. reference to hash of required changes,
                   11556: 3. domain
                   11557: 4. username
                   11558:   where domain,username are the domain of the portfolio owner 
                   11559:   (either a user or a course) 
                   11560: 
                   11561: Returns:
                   11562: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11563: 2. result of deletions ('ok' or 'error', with error message).
                   11564: 3. reference to hash of any new or updated access controls.
                   11565: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11566:    key = integer (inbound ID)
                   11567:    value = uniqueID  
1.747     albertel 11568: 
1.608     albertel 11569: =back
                   11570: 
1.243     albertel 11571: =head2 HTTP Helper Routines
                   11572: 
                   11573: =over 4
                   11574: 
1.191     harris41 11575: =item *
                   11576: 
                   11577: escape() : unpack non-word characters into CGI-compatible hex codes
                   11578: 
                   11579: =item *
                   11580: 
                   11581: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11582: 
1.243     albertel 11583: =back
                   11584: 
                   11585: =head1 PRIVATE SUBROUTINES
                   11586: 
                   11587: =head2 Underlying communication routines (Shouldn't call)
                   11588: 
                   11589: =over 4
                   11590: 
                   11591: =item *
                   11592: 
                   11593: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11594: 
                   11595: =item *
                   11596: 
                   11597: reply() : uses subreply to send a message to remote machine, logs all failures
                   11598: 
                   11599: =item *
                   11600: 
                   11601: critical() : passes a critical message to another server; if cannot
                   11602: get through then place message in connection buffer directory and
                   11603: returns con_delayed, if incapable of saving message, returns
                   11604: con_failed
                   11605: 
                   11606: =item *
                   11607: 
                   11608: reconlonc() : tries to reconnect lonc client processes.
                   11609: 
                   11610: =back
                   11611: 
                   11612: =head2 Resource Access Logging
                   11613: 
                   11614: =over 4
                   11615: 
                   11616: =item *
                   11617: 
                   11618: flushcourselogs() : flush (save) buffer logs and access logs
                   11619: 
                   11620: =item *
                   11621: 
                   11622: courselog($what) : save message for course in hash
                   11623: 
                   11624: =item *
                   11625: 
                   11626: courseacclog($what) : save message for course using &courselog().  Perform
                   11627: special processing for specific resource types (problems, exams, quizzes, etc).
                   11628: 
1.191     harris41 11629: =item *
                   11630: 
                   11631: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11632: as a PerlChildExitHandler
1.243     albertel 11633: 
                   11634: =back
                   11635: 
                   11636: =head2 Other
                   11637: 
                   11638: =over 4
                   11639: 
                   11640: =item *
                   11641: 
                   11642: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11643: 
                   11644: =back
                   11645: 
                   11646: =cut
1.877     foxr     11647: 

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