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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.7! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.6 2010/08/17 01:49:04 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.1056.4.5  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.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.619     albertel  102: require Exporter;
                    103: 
                    104: our @ISA = qw (Exporter);
                    105: our @EXPORT = qw(%env);
                    106: 
1.449     matthew   107: 
1.1       albertel  108: # --------------------------------------------------------------------- Logging
1.729     www       109: {
                    110:     my $logid;
                    111:     sub instructor_log {
1.957     raeburn   112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    113:         if (($cnum eq '') || ($cdom eq '')) {
                    114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    116:         }
1.729     www       117: 	$logid++;
1.957     raeburn   118:         my $now = time();
                    119: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       121: 				    { $id => {
                    122: 					'exe_uname' => $env{'user.name'},
                    123: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   124: 					'exe_time'  => $now,
1.730     www       125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    126: 					'delflag'   => $delflag,
                    127: 					'logentry'  => $storehash,
                    128: 					'uname'     => $uname,
                    129: 					'udom'      => $udom,
                    130: 				    }
1.957     raeburn   131: 				  },$cdom,$cnum);
1.729     www       132:     }
                    133: }
1.1       albertel  134: 
1.163     harris41  135: sub logtouch {
                    136:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  137:     unless (-e "$execdir/logs/lonnet.log") {	
                    138: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  139: 	close $fh;
                    140:     }
                    141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    143: }
                    144: 
1.1       albertel  145: sub logthis {
                    146:     my $message=shift;
                    147:     my $execdir=$perlvar{'lonDaemons'};
                    148:     my $now=time;
                    149:     my $local=localtime($now);
1.448     albertel  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    152: 	print $fh $logstring;
1.448     albertel  153: 	close($fh);
                    154:     }
1.1       albertel  155:     return 1;
                    156: }
                    157: 
                    158: sub logperm {
                    159:     my $message=shift;
                    160:     my $execdir=$perlvar{'lonDaemons'};
                    161:     my $now=time;
                    162:     my $local=localtime($now);
1.448     albertel  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    164: 	print $fh "$now:$message:$local\n";
                    165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
1.850     albertel  170: sub create_connection {
1.853     albertel  171:     my ($hostname,$lonid) = @_;
1.851     albertel  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  173: 				     Type    => SOCK_STREAM,
                    174: 				     Timeout => 10);
                    175:     return 0 if (!$client);
1.890     albertel  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  177:     my $result = <$client>;
                    178:     chomp($result);
                    179:     return 1 if ($result eq 'done');
                    180:     return 0;
                    181: }
                    182: 
1.983     raeburn   183: sub get_server_timezone {
                    184:     my ($cnum,$cdom) = @_;
                    185:     my $home=&homeserver($cnum,$cdom);
                    186:     if ($home ne 'no_host') {
                    187:         my $cachetime = 24*3600;
                    188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    189:         if (defined($cached)) {
                    190:             return $timezone;
                    191:         } else {
                    192:             my $timezone = &reply('servertimezone',$home);
                    193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    194:         }
                    195:     }
                    196: }
1.850     albertel  197: 
1.993     raeburn   198: sub get_server_loncaparev {
1.1056.4.3  raeburn   199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   200:     if (defined($lonhost)) {
                    201:         if (!defined(&hostname($lonhost))) {
                    202:             undef($lonhost);
                    203:         }
                    204:     }
                    205:     if (!defined($lonhost)) {
                    206:         if (defined(&domain($dom,'primary'))) {
                    207:             $lonhost=&domain($dom,'primary');
                    208:             if ($lonhost eq 'no_host') {
                    209:                 undef($lonhost);
                    210:             }
                    211:         }
                    212:     }
                    213:     if (defined($lonhost)) {
1.1056.4.3  raeburn   214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $loncaparev;
                    219:             }
                    220:         }
                    221:         my ($answer,$loncaparev);
                    222:         my @ids=&current_machine_ids();
                    223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    224:             $answer = $perlvar{'lonVersion'};
1.1056.4.7! raeburn   225:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   226:                 $loncaparev = $1;
                    227:             }
                    228:         } else {
                    229:             $answer = &reply('serverloncaparev',$lonhost);
                    230:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    231:                 if ($caller eq 'loncron') {
                    232:                     my $ua=new LWP::UserAgent;
                    233:                     $ua->timeout(20);
                    234:                     my $protocol = $protocol{$lonhost};
                    235:                     $protocol = 'http' if ($protocol ne 'https');
                    236:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    237:                     my $request=new HTTP::Request('GET',$url);
                    238:                     my $response=$ua->request($request);
                    239:                     unless ($response->is_error()) {
                    240:                         my $content = $response->content;
1.1056.4.7! raeburn   241:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   242:                             $loncaparev = $1;
                    243:                         }
                    244:                     }
                    245:                 } else {
                    246:                     $loncaparev = $loncaparevs{$lonhost};
                    247:                 }
1.1056.4.7! raeburn   248:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   249:                 $loncaparev = $1;
                    250:             }
                    251:         }
                    252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    253:     }
                    254: }
                    255: 
                    256: sub get_server_homeID {
                    257:     my ($hostname,$ignore_cache,$caller) = @_;
                    258:     unless ($ignore_cache) {
                    259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   260:         if (defined($cached)) {
1.1056.4.3  raeburn   261:             return $serverhomeID;
                    262:         }
                    263:     }
                    264:     my $cachetime = 12*3600;
                    265:     my $serverhomeID;
                    266:     if ($caller eq 'loncron') {
                    267:         my @machine_ids = &machine_ids($hostname);
                    268:         foreach my $id (@machine_ids) {
                    269:             my $response = &reply('serverhomeID',$id);
                    270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    271:                 $serverhomeID = $response;
                    272:                 last;
                    273:             }
1.993     raeburn   274:         }
1.1056.4.3  raeburn   275:         if ($serverhomeID eq '') {
                    276:             $serverhomeID = $machine_ids[-1];
                    277:         }
                    278:     } else {
                    279:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   280:     }
1.1056.4.3  raeburn   281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   282: }
                    283: 
1.1       albertel  284: # -------------------------------------------------- Non-critical communication
                    285: sub subreply {
                    286:     my ($cmd,$server)=@_;
1.838     albertel  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      288:     #
                    289:     #  With loncnew process trimming, there's a timing hole between lonc server
                    290:     #  process exit and the master server picking up the listen on the AF_UNIX
                    291:     #  socket.  In that time interval, a lock file will exist:
                    292: 
                    293:     my $lockfile=$peerfile.".lock";
                    294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    295: 	sleep(1);
                    296:     }
                    297:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      298:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      299:     #
1.550     foxr      300:     #   We'll give the connection a few tries before abandoning it.  If
                    301:     #   connection is not possible, we'll con_lost back to the client.
                    302:     #   
                    303:     my $client;
                    304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    306: 				      Type    => SOCK_STREAM,
                    307: 				      Timeout => 10);
1.869     albertel  308: 	if ($client) {
1.550     foxr      309: 	    last;		# Connected!
1.850     albertel  310: 	} else {
1.853     albertel  311: 	    &create_connection(&hostname($server),$server);
1.550     foxr      312: 	}
1.850     albertel  313:         sleep(1);		# Try again later if failed connection.
1.550     foxr      314:     }
                    315:     my $answer;
                    316:     if ($client) {
1.704     albertel  317: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      318: 	$answer=<$client>;
                    319: 	if (!$answer) { $answer="con_lost"; }
                    320: 	chomp($answer);
                    321:     } else {
                    322: 	$answer = 'con_lost';	# Failed connection.
                    323:     }
1.1       albertel  324:     return $answer;
                    325: }
                    326: 
                    327: sub reply {
                    328:     my ($cmd,$server)=@_;
1.838     albertel  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  330:     my $answer=subreply($cmd,$server);
1.65      www       331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  332:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       333:                 " $cmd to $server returned $answer</font>");
                    334:     }
1.1       albertel  335:     return $answer;
                    336: }
                    337: 
                    338: # ----------------------------------------------------------- Send USR1 to lonc
                    339: 
                    340: sub reconlonc {
1.891     albertel  341:     my ($lonid) = @_;
                    342:     my $hostname = &hostname($lonid);
                    343:     if ($lonid) {
                    344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    345: 	if ($hostname && -e $peerfile) {
                    346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    348: 					     Type    => SOCK_STREAM,
                    349: 					     Timeout => 10);
                    350: 	    if ($client) {
                    351: 		print $client ("reset_retries\n");
                    352: 		my $answer=<$client>;
                    353: 		#reset just this one.
                    354: 	    }
                    355: 	}
                    356: 	return;
                    357:     }
                    358: 
1.836     www       359:     &logthis("Trying to reconnect lonc");
1.1       albertel  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  361:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  362: 	my $loncpid=<$fh>;
                    363:         chomp($loncpid);
                    364:         if (kill 0 => $loncpid) {
                    365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    366:             kill USR1 => $loncpid;
                    367:             sleep 1;
1.836     www       368:          } else {
1.12      www       369: 	    &logthis(
1.672     albertel  370:                "<font color=\"blue\">WARNING:".
1.12      www       371:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  372:         }
                    373:     } else {
1.836     www       374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  375:     }
                    376: }
                    377: 
                    378: # ------------------------------------------------------ Critical communication
1.12      www       379: 
1.1       albertel  380: sub critical {
                    381:     my ($cmd,$server)=@_;
1.838     albertel  382:     unless (&hostname($server)) {
1.672     albertel  383:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       384:                " Critical message to unknown server ($server)</font>");
                    385:         return 'no_such_host';
                    386:     }
1.1       albertel  387:     my $answer=reply($cmd,$server);
                    388:     if ($answer eq 'con_lost') {
                    389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  390: 	my $answer=reply($cmd,$server);
1.1       albertel  391:         if ($answer eq 'con_lost') {
                    392:             my $now=time;
                    393:             my $middlename=$cmd;
1.5       www       394:             $middlename=substr($middlename,0,16);
1.1       albertel  395:             $middlename=~s/\W//g;
                    396:             my $dfilename=
1.305     www       397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    398:             $dumpcount++;
1.1       albertel  399:             {
1.448     albertel  400: 		my $dfh;
                    401: 		if (open($dfh,">$dfilename")) {
                    402: 		    print $dfh "$cmd\n"; 
                    403: 		    close($dfh);
                    404: 		}
1.1       albertel  405:             }
                    406:             sleep 2;
                    407:             my $wcmd='';
                    408:             {
1.448     albertel  409: 		my $dfh;
                    410: 		if (open($dfh,"<$dfilename")) {
                    411: 		    $wcmd=<$dfh>; 
                    412: 		    close($dfh);
                    413: 		}
1.1       albertel  414:             }
                    415:             chomp($wcmd);
1.7       www       416:             if ($wcmd eq $cmd) {
1.672     albertel  417: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       418:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  419:                 &logperm("D:$server:$cmd");
                    420: 	        return 'con_delayed';
                    421:             } else {
1.672     albertel  422:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       423:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  424:                 &logperm("F:$server:$cmd");
                    425:                 return 'con_failed';
                    426:             }
                    427:         }
                    428:     }
                    429:     return $answer;
1.405     albertel  430: }
                    431: 
1.755     albertel  432: # ------------------------------------------- check if return value is an error
                    433: 
                    434: sub error {
                    435:     my ($result) = @_;
1.756     albertel  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  437: 	if ($2 == 2) { return undef; }
                    438: 	return $1;
                    439:     }
                    440:     return undef;
                    441: }
                    442: 
1.783     albertel  443: sub convert_and_load_session_env {
                    444:     my ($lonidsdir,$handle)=@_;
                    445:     my @profile;
                    446:     {
1.917     albertel  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    448: 	if (!$opened) {
1.915     albertel  449: 	    return 0;
                    450: 	}
1.783     albertel  451: 	flock($idf,LOCK_SH);
                    452: 	@profile=<$idf>;
                    453: 	close($idf);
                    454:     }
                    455:     my %temp_env;
                    456:     foreach my $line (@profile) {
1.786     albertel  457: 	if ($line !~ m/=/) {
                    458: 	    return 0;
                    459: 	}
1.783     albertel  460: 	chomp($line);
                    461: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    463:     }
                    464:     unlink("$lonidsdir/$handle.id");
                    465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    466: 	    0640)) {
                    467: 	%disk_env = %temp_env;
                    468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    469: 	untie(%disk_env);
                    470:     }
1.786     albertel  471:     return 1;
1.783     albertel  472: }
                    473: 
1.374     www       474: # ------------------------------------------- Transfer profile into environment
1.780     albertel  475: my $env_loaded;
                    476: sub transfer_profile_to_env {
1.788     albertel  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    478:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       479: 
1.720     albertel  480:     if (!defined($lonidsdir)) {
                    481: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    482:     }
                    483:     if (!defined($handle)) {
                    484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    485:     }
                    486: 
1.786     albertel  487:     my $convert;
                    488:     {
1.917     albertel  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    490: 	if (!$opened) {
1.915     albertel  491: 	    return;
                    492: 	}
1.786     albertel  493: 	flock($idf,LOCK_SH);
                    494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    495: 		&GDBM_READER(),0640)) {
                    496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    497: 	    untie(%disk_env);
                    498: 	} else {
                    499: 	    $convert = 1;
                    500: 	}
                    501:     }
                    502:     if ($convert) {
                    503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    504: 	    &logthis("Failed to load session, or convert session.");
                    505: 	}
1.374     www       506:     }
1.783     albertel  507: 
1.786     albertel  508:     my %remove;
1.783     albertel  509:     while ( my $envname = each(%env) ) {
1.433     matthew   510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    511:             if ($time < time-300) {
1.783     albertel  512:                 $remove{$key}++;
1.433     matthew   513:             }
                    514:         }
                    515:     }
1.783     albertel  516: 
1.619     albertel  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  518:     $env_loaded=1;
1.783     albertel  519:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   520:         &delenv($expired_key);
1.374     www       521:     }
1.1       albertel  522: }
                    523: 
1.916     albertel  524: # ---------------------------------------------------- Check for valid session 
                    525: sub check_for_valid_session {
                    526:     my ($r) = @_;
                    527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    528:     my $lonid=$cookies{'lonID'};
                    529:     return undef if (!$lonid);
                    530: 
                    531:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    532:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    533:     return undef if (!-e "$lonidsdir/$handle.id");
                    534: 
1.917     albertel  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    536:     return undef if (!$opened);
1.916     albertel  537: 
                    538:     flock($idf,LOCK_SH);
                    539:     my %disk_env;
                    540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    541: 	    &GDBM_READER(),0640)) {
                    542: 	return undef;	
                    543:     }
                    544: 
                    545:     if (!defined($disk_env{'user.name'})
                    546: 	|| !defined($disk_env{'user.domain'})) {
                    547: 	return undef;
                    548:     }
                    549:     return $handle;
                    550: }
                    551: 
1.830     albertel  552: sub timed_flock {
                    553:     my ($file,$lock_type) = @_;
                    554:     my $failed=0;
                    555:     eval {
                    556: 	local $SIG{__DIE__}='DEFAULT';
                    557: 	local $SIG{ALRM}=sub {
                    558: 	    $failed=1;
                    559: 	    die("failed lock");
                    560: 	};
                    561: 	alarm(13);
                    562: 	flock($file,$lock_type);
                    563: 	alarm(0);
                    564:     };
                    565:     if ($failed) {
                    566: 	return undef;
                    567:     } else {
                    568: 	return 1;
                    569:     }
                    570: }
                    571: 
1.5       www       572: # ---------------------------------------------------------- Append Environment
                    573: 
                    574: sub appenv {
1.949     raeburn   575:     my ($newenv,$roles) = @_;
                    576:     if (ref($newenv) eq 'HASH') {
                    577:         foreach my $key (keys(%{$newenv})) {
                    578:             my $refused = 0;
                    579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    580:                 $refused = 1;
                    581:                 if (ref($roles) eq 'ARRAY') {
                    582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    584:                         $refused = 0;
                    585:                     }
                    586:                 }
                    587:             }
                    588:             if ($refused) {
                    589:                 &logthis("<font color=\"blue\">WARNING: ".
                    590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    591:                          .'</font>');
                    592: 	        delete($newenv->{$key});
                    593:             } else {
                    594:                 $env{$key}=$newenv->{$key};
                    595:             }
                    596:         }
                    597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    598:         if ($opened
                    599: 	    && &timed_flock($env_file,LOCK_EX)
                    600: 	    &&
                    601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    603: 	    while (my ($key,$value) = each(%{$newenv})) {
                    604: 	        $disk_env{$key} = $value;
                    605: 	    }
                    606: 	    untie(%disk_env);
1.35      www       607:         }
1.191     harris41  608:     }
1.56      www       609:     return 'ok';
                    610: }
                    611: # ----------------------------------------------------- Delete from Environment
                    612: 
                    613: sub delenv {
1.987     raeburn   614:     my ($delthis,$regexp) = @_;
1.56      www       615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  616:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       617:                 "Attempt to delete from environment ".$delthis);
                    618:         return 'error';
                    619:     }
1.917     albertel  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    621:     if ($opened
1.915     albertel  622: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  623: 	&&
                    624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  626: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   627: 	    if ($regexp) {
                    628:                 if ($key=~/^$delthis/) {
                    629:                     delete($env{$key});
                    630:                     delete($disk_env{$key});
                    631:                 } 
                    632:             } else {
                    633:                 if ($key=~/^\Q$delthis\E/) {
                    634: 		    delete($env{$key});
                    635: 		    delete($disk_env{$key});
                    636: 	        }
                    637:             }
1.448     albertel  638: 	}
1.783     albertel  639: 	untie(%disk_env);
1.5       www       640:     }
                    641:     return 'ok';
1.369     albertel  642: }
                    643: 
1.790     albertel  644: sub get_env_multiple {
                    645:     my ($name) = @_;
                    646:     my @values;
                    647:     if (defined($env{$name})) {
                    648:         # exists is it an array
                    649:         if (ref($env{$name})) {
                    650:             @values=@{ $env{$name} };
                    651:         } else {
                    652:             $values[0]=$env{$name};
                    653:         }
                    654:     }
                    655:     return(@values);
                    656: }
                    657: 
1.958     www       658: # ------------------------------------------------------------------- Locking
                    659: 
                    660: sub set_lock {
                    661:     my ($text)=@_;
                    662:     $locknum++;
                    663:     my $id=$$.'-'.$locknum;
                    664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    665:              'session.lock.'.$id => $text});
                    666:     return $id;
                    667: }
                    668: 
                    669: sub get_locks {
                    670:     my $num=0;
                    671:     my %texts=();
                    672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    673:        if ($lock=~/\w/) {
                    674:           $num++;
                    675:           $texts{$lock}=$env{'session.lock.'.$lock};
                    676:        }
                    677:    }
                    678:    return ($num,%texts);
                    679: }
                    680: 
                    681: sub remove_lock {
                    682:     my ($id)=@_;
                    683:     my $newlocks='';
                    684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    685:        if (($lock=~/\w/) && ($lock ne $id)) {
                    686:           $newlocks.=','.$lock;
                    687:        }
                    688:     }
                    689:     &appenv({'session.locks' => $newlocks});
                    690:     &delenv('session.lock.'.$id);
                    691: }
                    692: 
                    693: sub remove_all_locks {
                    694:     my $activelocks=$env{'session.locks'};
                    695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    696:        if ($lock=~/\w/) {
                    697:           &remove_lock($lock);
                    698:        }
                    699:     }
                    700: }
                    701: 
                    702: 
1.369     albertel  703: # ------------------------------------------ Find out current server userload
                    704: sub userload {
                    705:     my $numusers=0;
                    706:     {
                    707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    708: 	my $filename;
                    709: 	my $curtime=time;
                    710: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  711: 	    next if ($filename eq '.' || $filename eq '..');
                    712: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  715: 	}
                    716: 	closedir(LONIDS);
                    717:     }
                    718:     my $userloadpercent=0;
                    719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    720:     if ($maxuserload) {
1.371     albertel  721: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  722:     }
1.372     albertel  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  724:     return $userloadpercent;
1.283     www       725: }
                    726: 
                    727: # ------------------------------------------ Fight off request when overloaded
                    728: 
                    729: sub overloaderror {
                    730:     my ($r,$checkserver)=@_;
                    731:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    732:     my $loadavg;
                    733:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  734:        open(my $loadfile,'/proc/loadavg');
1.283     www       735:        $loadavg=<$loadfile>;
                    736:        $loadavg =~ s/\s.*//g;
1.285     matthew   737:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  738:        close($loadfile);
1.283     www       739:     } else {
                    740:        $loadavg=&reply('load',$checkserver);
                    741:     }
1.285     matthew   742:     my $overload=$loadavg-100;
1.283     www       743:     if ($overload>0) {
1.285     matthew   744: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       745:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       746:         return 413;
1.283     www       747:     }    
                    748:     return '';
1.5       www       749: }
1.1       albertel  750: 
                    751: # ------------------------------ Find server with least workload from spare.tab
1.11      www       752: 
1.1       albertel  753: sub spareserver {
1.670     albertel  754:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  755:     my $spare_server;
1.370     albertel  756:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  757:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    758:                                                      :  $userloadpercent;
                    759:     
                    760:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    761: 	($spare_server, $lowest_load) =
                    762: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    763:     }
                    764: 
                    765:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    766: 
                    767:     if (!$found_server) {
                    768: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    769: 	    ($spare_server, $lowest_load) =
                    770: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    771: 	}
                    772:     }
                    773: 
                    774:     if (!$want_server_name) {
1.968     raeburn   775:         my $protocol = 'http';
                    776:         if ($protocol{$spare_server} eq 'https') {
                    777:             $protocol = $protocol{$spare_server};
                    778:         }
1.1001    raeburn   779:         if (defined($spare_server)) {
                    780:             my $hostname = &hostname($spare_server);
                    781:             if (defined($hostname)) {  
                    782: 	        $spare_server = $protocol.'://'.$hostname;
                    783:             }
                    784:         }
1.784     albertel  785:     }
                    786:     return $spare_server;
                    787: }
                    788: 
                    789: sub compare_server_load {
                    790:     my ($try_server, $spare_server, $lowest_load) = @_;
                    791: 
                    792:     my $loadans     = &reply('load',    $try_server);
                    793:     my $userloadans = &reply('userload',$try_server);
                    794: 
                    795:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3  raeburn   796:         return; #didn't get a number from the server
1.784     albertel  797:     }
                    798: 
                    799:     my $load;
                    800:     if ($loadans =~ /\d/) {
                    801: 	if ($userloadans =~ /\d/) {
                    802: 	    #both are numbers, pick the bigger one
                    803: 	    $load = ($loadans > $userloadans) ? $loadans 
                    804: 		                              : $userloadans;
1.411     albertel  805: 	} else {
1.784     albertel  806: 	    $load = $loadans;
1.411     albertel  807: 	}
1.784     albertel  808:     } else {
                    809: 	$load = $userloadans;
                    810:     }
                    811: 
                    812:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    813: 	$spare_server = $try_server;
                    814: 	$lowest_load  = $load;
1.370     albertel  815:     }
1.784     albertel  816:     return ($spare_server,$lowest_load);
1.202     matthew   817: }
1.914     albertel  818: 
                    819: # --------------------------- ask offload servers if user already has a session
                    820: sub find_existing_session {
                    821:     my ($udom,$uname) = @_;
                    822:     foreach my $try_server (@{ $spareid{'primary'} },
                    823: 			    @{ $spareid{'default'} }) {
                    824: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    825:     }
                    826:     return;
                    827: }
                    828: 
                    829: # -------------------------------- ask if server already has a session for user
                    830: sub has_user_session {
                    831:     my ($lonid,$udom,$uname) = @_;
                    832:     my $result = &reply(join(':','userhassession',
                    833: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    834:     return 1 if ($result eq 'ok');
                    835: 
                    836:     return 0;
                    837: }
                    838: 
1.1056.4.3  raeburn   839: # --------- determine least loaded server in a user's domain which allows login
                    840: 
                    841: sub choose_server {
                    842:     my ($udom) = @_;
                    843:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    844:     my %servers = &get_servers($udom);
                    845:     my $lowest_load = 30000;
                    846:     my ($login_host,$hostname);
                    847:     foreach my $lonhost (keys(%servers)) {
                    848:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    849:         if ($loginvia eq '') {
                    850:             ($login_host, $lowest_load) =
                    851:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    852:         }
                    853:     }
                    854:     if ($login_host ne '') {
                    855:         $hostname = $servers{$login_host};
                    856:     }
                    857:     return ($login_host,$hostname);
                    858: }
                    859: 
1.202     matthew   860: # --------------------------------------------- Try to change a user's password
                    861: 
                    862: sub changepass {
1.799     raeburn   863:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   864:     $currentpass = &escape($currentpass);
                    865:     $newpass     = &escape($newpass);
1.1030    raeburn   866:     my $lonhost = $perlvar{'lonHostID'};
                    867:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   868: 		       $server);
                    869:     if (! $answer) {
                    870: 	&logthis("No reply on password change request to $server ".
                    871: 		 "by $uname in domain $udom.");
                    872:     } elsif ($answer =~ "^ok") {
                    873:         &logthis("$uname in $udom successfully changed their password ".
                    874: 		 "on $server.");
                    875:     } elsif ($answer =~ "^pwchange_failure") {
                    876: 	&logthis("$uname in $udom was unable to change their password ".
                    877: 		 "on $server.  The action was blocked by either lcpasswd ".
                    878: 		 "or pwchange");
                    879:     } elsif ($answer =~ "^non_authorized") {
                    880:         &logthis("$uname in $udom did not get their password correct when ".
                    881: 		 "attempting to change it on $server.");
                    882:     } elsif ($answer =~ "^auth_mode_error") {
                    883:         &logthis("$uname in $udom attempted to change their password despite ".
                    884: 		 "not being locally or internally authenticated on $server.");
                    885:     } elsif ($answer =~ "^unknown_user") {
                    886:         &logthis("$uname in $udom attempted to change their password ".
                    887: 		 "on $server but were unable to because $server is not ".
                    888: 		 "their home server.");
                    889:     } elsif ($answer =~ "^refused") {
                    890: 	&logthis("$server refused to change $uname in $udom password because ".
                    891: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   892:     } elsif ($answer =~ "invalid_client") {
                    893:         &logthis("$server refused to change $uname in $udom password because ".
                    894:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   895:     }
                    896:     return $answer;
1.1       albertel  897: }
                    898: 
1.169     harris41  899: # ----------------------- Try to determine user's current authentication scheme
                    900: 
                    901: sub queryauthenticate {
                    902:     my ($uname,$udom)=@_;
1.456     albertel  903:     my $uhome=&homeserver($uname,$udom);
                    904:     if (!$uhome) {
                    905: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    906: 	return 'no_host';
                    907:     }
                    908:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    909:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    910: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  911:     }
1.456     albertel  912:     return $answer;
1.169     harris41  913: }
                    914: 
1.1       albertel  915: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       916: 
1.1       albertel  917: sub authenticate {
1.1056.4.3  raeburn   918:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  919:     $upass=&escape($upass);
                    920:     $uname= &LONCAPA::clean_username($uname);
1.836     www       921:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   922:     my $newhome;
1.836     www       923:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    924: # Maybe the machine was offline and only re-appeared again recently?
                    925:         &reconlonc();
                    926: # One more
1.952     raeburn   927: 	$uhome=&homeserver($uname,$udom,1);
                    928:         if (($uhome eq 'no_host') && $checkdefauth) {
                    929:             if (defined(&domain($udom,'primary'))) {
                    930:                 $newhome=&domain($udom,'primary');
                    931:             }
                    932:             if ($newhome ne '') {
                    933:                 $uhome = $newhome;
                    934:             }
                    935:         }
1.836     www       936: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    937: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   938: 	    return 'no_host';
                    939:         }
1.1       albertel  940:     }
1.1056.4.3  raeburn   941:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  942:     if ($answer eq 'authorized') {
1.952     raeburn   943:         if ($newhome) {
                    944:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    945:             return 'no_account_on_host'; 
                    946:         } else {
                    947:             &logthis("User $uname at $udom authorized by $uhome");
                    948:             return $uhome;
                    949:         }
1.471     albertel  950:     }
                    951:     if ($answer eq 'non_authorized') {
                    952: 	&logthis("User $uname at $udom rejected by $uhome");
                    953: 	return 'no_host'; 
1.9       www       954:     }
1.471     albertel  955:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  956:     return 'no_host';
                    957: }
                    958: 
1.1056.4.3  raeburn   959: sub can_host_session {
                    960:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    961:     my $canhost = 1;
                    962:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                    963:     if (ref($remotesessions) eq 'HASH') {
                    964:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                    965:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                    966:                 $canhost = 0;
                    967:             } else {
                    968:                 $canhost = 1;
                    969:             }
                    970:         }
                    971:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                    972:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                    973:                 $canhost = 1;
                    974:             } else {
                    975:                 $canhost = 0;
                    976:             }
                    977:         }
                    978:         if ($canhost) {
                    979:             if ($remotesessions->{'version'} ne '') {
                    980:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    981:                 if ($reqmajor ne '' && $reqminor ne '') {
                    982:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    983:                         my $major = $1;
                    984:                         my $minor = $2;
                    985:                         if (($major < $reqmajor ) ||
                    986:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                    987:                             $canhost = 0;
                    988:                         }
                    989:                     } else {
                    990:                         $canhost = 0;
                    991:                     }
                    992:                 }
                    993:             }
                    994:         }
                    995:     }
                    996:     if ($canhost) {
                    997:         if (ref($hostedsessions) eq 'HASH') {
                    998:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                    999:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1000:                     $canhost = 0;
                   1001:                 } else {
                   1002:                     $canhost = 1;
                   1003:                 }
                   1004:             }
                   1005:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1006:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1007:                     $canhost = 1;
                   1008:                 } else {
                   1009:                     $canhost = 0;
                   1010:                 }
                   1011:             }
                   1012:         }
                   1013:     }
                   1014:     return $canhost;
                   1015: }
                   1016: 
1.1       albertel 1017: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1018: 
1.599     albertel 1019: my %homecache;
1.1       albertel 1020: sub homeserver {
1.230     stredwic 1021:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1022:     my $index="$uname:$udom";
1.426     albertel 1023: 
1.599     albertel 1024:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1025: 
                   1026:     my %servers = &get_servers($udom,'library');
                   1027:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1028:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1029: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1030: 
                   1031: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1032: 	if ($answer eq 'found') {
                   1033: 	    delete($badServerCache{$tryserver}); 
                   1034: 	    return $homecache{$index}=$tryserver;
                   1035: 	} elsif ($answer eq 'no_host') {
                   1036: 	    $badServerCache{$tryserver}=1;
                   1037: 	}
1.1       albertel 1038:     }    
                   1039:     return 'no_host';
1.70      www      1040: }
                   1041: 
                   1042: # ------------------------------------- Find the usernames behind a list of IDs
                   1043: 
                   1044: sub idget {
                   1045:     my ($udom,@ids)=@_;
                   1046:     my %returnhash=();
                   1047:     
1.841     albertel 1048:     my %servers = &get_servers($udom,'library');
                   1049:     foreach my $tryserver (keys(%servers)) {
                   1050: 	my $idlist=join('&',@ids);
                   1051: 	$idlist=~tr/A-Z/a-z/; 
                   1052: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1053: 	my @answer=();
                   1054: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1055: 	    @answer=split(/\&/,$reply);
                   1056: 	}                    ;
                   1057: 	my $i;
                   1058: 	for ($i=0;$i<=$#ids;$i++) {
                   1059: 	    if ($answer[$i]) {
                   1060: 		$returnhash{$ids[$i]}=$answer[$i];
                   1061: 	    } 
                   1062: 	}
                   1063:     } 
1.70      www      1064:     return %returnhash;
                   1065: }
                   1066: 
                   1067: # ------------------------------------- Find the IDs behind a list of usernames
                   1068: 
                   1069: sub idrget {
                   1070:     my ($udom,@unames)=@_;
                   1071:     my %returnhash=();
1.800     albertel 1072:     foreach my $uname (@unames) {
                   1073:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1074:     }
1.70      www      1075:     return %returnhash;
                   1076: }
                   1077: 
                   1078: # ------------------------------- Store away a list of names and associated IDs
                   1079: 
                   1080: sub idput {
                   1081:     my ($udom,%ids)=@_;
                   1082:     my %servers=();
1.800     albertel 1083:     foreach my $uname (keys(%ids)) {
                   1084: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1085:         my $uhom=&homeserver($uname,$udom);
1.70      www      1086:         if ($uhom ne 'no_host') {
1.800     albertel 1087:             my $id=&escape($ids{$uname});
1.70      www      1088:             $id=~tr/A-Z/a-z/;
1.800     albertel 1089:             my $esc_unam=&escape($uname);
1.70      www      1090: 	    if ($servers{$uhom}) {
1.800     albertel 1091: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1092:             } else {
1.800     albertel 1093:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1094:             }
                   1095:         }
1.191     harris41 1096:     }
1.800     albertel 1097:     foreach my $server (keys(%servers)) {
                   1098:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1099:     }
1.344     www      1100: }
                   1101: 
1.1023    raeburn  1102: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1103: sub dump_dom {
1.1023    raeburn  1104:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1105:     if (!$udom) {
                   1106:         $udom=$env{'user.domain'};
                   1107:     }
                   1108:     my %returnhash;
1.1023    raeburn  1109:     if ($udom) {
                   1110:         my $uname = &get_domainconfiguser($udom);
                   1111:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1112:     }
                   1113:     return %returnhash;
                   1114: }
                   1115: 
1.1023    raeburn  1116: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1117: 
                   1118: sub get_dom {
1.860     raeburn  1119:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1120:     my $items='';
                   1121:     foreach my $item (@$storearr) {
                   1122:         $items.=&escape($item).'&';
                   1123:     }
                   1124:     $items=~s/\&$//;
1.860     raeburn  1125:     if (!$udom) {
                   1126:         $udom=$env{'user.domain'};
                   1127:         if (defined(&domain($udom,'primary'))) {
                   1128:             $uhome=&domain($udom,'primary');
                   1129:         } else {
1.874     albertel 1130:             undef($uhome);
1.860     raeburn  1131:         }
                   1132:     } else {
                   1133:         if (!$uhome) {
                   1134:             if (defined(&domain($udom,'primary'))) {
                   1135:                 $uhome=&domain($udom,'primary');
                   1136:             }
                   1137:         }
                   1138:     }
                   1139:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1140:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1141:         my %returnhash;
1.875     albertel 1142:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1143:             return %returnhash;
                   1144:         }
1.806     raeburn  1145:         my @pairs=split(/\&/,$rep);
                   1146:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1147:             return @pairs;
                   1148:         }
                   1149:         my $i=0;
                   1150:         foreach my $item (@$storearr) {
                   1151:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1152:             $i++;
                   1153:         }
                   1154:         return %returnhash;
                   1155:     } else {
1.880     banghart 1156:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1157:     }
                   1158: }
                   1159: 
                   1160: # -------------------------------------------- put items in domain db files 
                   1161: 
                   1162: sub put_dom {
1.860     raeburn  1163:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1164:     if (!$udom) {
                   1165:         $udom=$env{'user.domain'};
                   1166:         if (defined(&domain($udom,'primary'))) {
                   1167:             $uhome=&domain($udom,'primary');
                   1168:         } else {
1.874     albertel 1169:             undef($uhome);
1.860     raeburn  1170:         }
                   1171:     } else {
                   1172:         if (!$uhome) {
                   1173:             if (defined(&domain($udom,'primary'))) {
                   1174:                 $uhome=&domain($udom,'primary');
                   1175:             }
                   1176:         }
                   1177:     } 
                   1178:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1179:         my $items='';
                   1180:         foreach my $item (keys(%$storehash)) {
                   1181:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1182:         }
                   1183:         $items=~s/\&$//;
                   1184:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1185:     } else {
1.860     raeburn  1186:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1187:     }
                   1188: }
                   1189: 
1.1023    raeburn  1190: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1191: sub newput_dom {
1.1023    raeburn  1192:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1193:     my $result;
                   1194:     if (!$udom) {
                   1195:         $udom=$env{'user.domain'};
                   1196:     }
1.1023    raeburn  1197:     if ($udom) {
                   1198:         my $uname = &get_domainconfiguser($udom);
                   1199:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1200:     }
                   1201:     return $result;
                   1202: }
                   1203: 
1.1023    raeburn  1204: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1205: sub del_dom {
1.1023    raeburn  1206:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1207:     if (ref($storearr) eq 'ARRAY') {
                   1208:         if (!$udom) {
                   1209:             $udom=$env{'user.domain'};
                   1210:         }
1.1023    raeburn  1211:         if ($udom) {
                   1212:             my $uname = &get_domainconfiguser($udom); 
                   1213:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1214:         }
                   1215:     }
                   1216: }
                   1217: 
1.1023    raeburn  1218: # ----------------------------------construct domainconfig user for a domain 
                   1219: sub get_domainconfiguser {
                   1220:     my ($udom) = @_;
                   1221:     return $udom.'-domainconfig';
                   1222: }
                   1223: 
1.837     raeburn  1224: sub retrieve_inst_usertypes {
                   1225:     my ($udom) = @_;
                   1226:     my (%returnhash,@order);
1.989     raeburn  1227:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1228:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1229:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1230:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1231:         @order = @{$domdefs{'inststatusorder'}};
                   1232:     } else {
                   1233:         if (defined(&domain($udom,'primary'))) {
                   1234:             my $uhome=&domain($udom,'primary');
                   1235:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1236:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1237:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1238:                 return (\%returnhash,\@order);
                   1239:             }
                   1240:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1241:             my @pairs=split(/\&/,$hashitems);
                   1242:             foreach my $item (@pairs) {
                   1243:                 my ($key,$value)=split(/=/,$item,2);
                   1244:                 $key = &unescape($key);
                   1245:                 next if ($key =~ /^error: 2 /);
                   1246:                 $returnhash{$key}=&thaw_unescape($value);
                   1247:             }
                   1248:             my @esc_order = split(/\&/,$orderitems);
                   1249:             foreach my $item (@esc_order) {
                   1250:                 push(@order,&unescape($item));
                   1251:             }
                   1252:         } else {
                   1253:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1254:         }
                   1255:     }
                   1256:     return (\%returnhash,\@order);
                   1257: }
                   1258: 
1.868     raeburn  1259: sub is_domainimage {
                   1260:     my ($url) = @_;
                   1261:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1262:         if (&domain($1) ne '') {
                   1263:             return '1';
                   1264:         }
                   1265:     }
                   1266:     return;
                   1267: }
                   1268: 
1.899     raeburn  1269: sub inst_directory_query {
                   1270:     my ($srch) = @_;
                   1271:     my $udom = $srch->{'srchdomain'};
                   1272:     my %results;
                   1273:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1274:     my $outcome;
1.899     raeburn  1275:     if ($homeserver ne '') {
1.904     albertel 1276: 	my $queryid=&reply("querysend:instdirsearch:".
                   1277: 			   &escape($srch->{'srchby'}).':'.
                   1278: 			   &escape($srch->{'srchterm'}).':'.
                   1279: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1280: 	my $host=&hostname($homeserver);
                   1281: 	if ($queryid !~/^\Q$host\E\_/) {
                   1282: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1283: 	    return;
                   1284: 	}
                   1285: 	my $response = &get_query_reply($queryid);
                   1286: 	my $maxtries = 5;
                   1287: 	my $tries = 1;
                   1288: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1289: 	    $response = &get_query_reply($queryid);
                   1290: 	    $tries ++;
                   1291: 	}
                   1292: 
                   1293:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1294:             if ($response eq 'unavailable') {
                   1295:                 $outcome = $response;
                   1296:             } else {
                   1297:                 $outcome = 'ok';
                   1298:                 my @matches = split(/\n/,$response);
                   1299:                 foreach my $match (@matches) {
                   1300:                     my ($key,$value) = split(/=/,$match);
                   1301:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1302:                 }
1.899     raeburn  1303:             }
                   1304:         }
                   1305:     }
1.909     raeburn  1306:     return ($outcome,%results);
1.899     raeburn  1307: }
                   1308: 
                   1309: sub usersearch {
                   1310:     my ($srch) = @_;
                   1311:     my $dom = $srch->{'srchdomain'};
                   1312:     my %results;
                   1313:     my %libserv = &all_library();
                   1314:     my $query = 'usersearch';
                   1315:     foreach my $tryserver (keys(%libserv)) {
                   1316:         if (&host_domain($tryserver) eq $dom) {
                   1317:             my $host=&hostname($tryserver);
                   1318:             my $queryid=
1.911     raeburn  1319:                 &reply("querysend:".&escape($query).':'.
                   1320:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1321:                        &escape($srch->{'srchtype'}).':'.
                   1322:                        &escape($srch->{'srchterm'}),$tryserver);
                   1323:             if ($queryid !~/^\Q$host\E\_/) {
                   1324:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1325:                 next;
1.899     raeburn  1326:             }
                   1327:             my $reply = &get_query_reply($queryid);
                   1328:             my $maxtries = 1;
                   1329:             my $tries = 1;
                   1330:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1331:                 $reply = &get_query_reply($queryid);
                   1332:                 $tries ++;
                   1333:             }
                   1334:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1335:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1336:             } else {
1.911     raeburn  1337:                 my @matches;
                   1338:                 if ($reply =~ /\n/) {
                   1339:                     @matches = split(/\n/,$reply);
                   1340:                 } else {
                   1341:                     @matches = split(/\&/,$reply);
                   1342:                 }
1.899     raeburn  1343:                 foreach my $match (@matches) {
                   1344:                     my ($uname,$udom,%userhash);
1.911     raeburn  1345:                     foreach my $entry (split(/:/,$match)) {
                   1346:                         my ($key,$value) =
                   1347:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1348:                         $userhash{$key} = $value;
                   1349:                         if ($key eq 'username') {
                   1350:                             $uname = $value;
                   1351:                         } elsif ($key eq 'domain') {
                   1352:                             $udom = $value;
1.911     raeburn  1353:                         }
1.899     raeburn  1354:                     }
                   1355:                     $results{$uname.':'.$udom} = \%userhash;
                   1356:                 }
                   1357:             }
                   1358:         }
                   1359:     }
                   1360:     return %results;
                   1361: }
                   1362: 
1.912     raeburn  1363: sub get_instuser {
                   1364:     my ($udom,$uname,$id) = @_;
                   1365:     my $homeserver = &domain($udom,'primary');
                   1366:     my ($outcome,%results);
                   1367:     if ($homeserver ne '') {
                   1368:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1369:                            &escape($id).':'.&escape($udom),$homeserver);
                   1370:         my $host=&hostname($homeserver);
                   1371:         if ($queryid !~/^\Q$host\E\_/) {
                   1372:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1373:             return;
                   1374:         }
                   1375:         my $response = &get_query_reply($queryid);
                   1376:         my $maxtries = 5;
                   1377:         my $tries = 1;
                   1378:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1379:             $response = &get_query_reply($queryid);
                   1380:             $tries ++;
                   1381:         }
                   1382:         if (!&error($response) && $response ne 'refused') {
                   1383:             if ($response eq 'unavailable') {
                   1384:                 $outcome = $response;
                   1385:             } else {
                   1386:                 $outcome = 'ok';
                   1387:                 my @matches = split(/\n/,$response);
                   1388:                 foreach my $match (@matches) {
                   1389:                     my ($key,$value) = split(/=/,$match);
                   1390:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
                   1395:     my %userinfo;
                   1396:     if (ref($results{$uname}) eq 'HASH') {
                   1397:         %userinfo = %{$results{$uname}};
                   1398:     } 
                   1399:     return ($outcome,%userinfo);
                   1400: }
                   1401: 
                   1402: sub inst_rulecheck {
1.923     raeburn  1403:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1404:     my %returnhash;
                   1405:     if ($udom ne '') {
                   1406:         if (ref($rules) eq 'ARRAY') {
                   1407:             @{$rules} = map {&escape($_);} (@{$rules});
                   1408:             my $rulestr = join(':',@{$rules});
                   1409:             my $homeserver=&domain($udom,'primary');
                   1410:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1411:                 my $response;
                   1412:                 if ($item eq 'username') {                
                   1413:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1414:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1415:                                               $homeserver));
1.923     raeburn  1416:                 } elsif ($item eq 'id') {
                   1417:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1418:                                               ':'.&escape($id).':'.$rulestr,
                   1419:                                               $homeserver));
1.945     raeburn  1420:                 } elsif ($item eq 'selfcreate') {
                   1421:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1422:                                                &escape($udom).':'.&escape($uname).
                   1423:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1424:                 }
1.912     raeburn  1425:                 if ($response ne 'refused') {
                   1426:                     my @pairs=split(/\&/,$response);
                   1427:                     foreach my $item (@pairs) {
                   1428:                         my ($key,$value)=split(/=/,$item,2);
                   1429:                         $key = &unescape($key);
                   1430:                         next if ($key =~ /^error: 2 /);
                   1431:                         $returnhash{$key}=&thaw_unescape($value);
                   1432:                     }
                   1433:                 }
                   1434:             }
                   1435:         }
                   1436:     }
                   1437:     return %returnhash;
                   1438: }
                   1439: 
                   1440: sub inst_userrules {
1.923     raeburn  1441:     my ($udom,$check) = @_;
1.912     raeburn  1442:     my (%ruleshash,@ruleorder);
                   1443:     if ($udom ne '') {
                   1444:         my $homeserver=&domain($udom,'primary');
                   1445:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1446:             my $response;
                   1447:             if ($check eq 'id') {
                   1448:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1449:                                  $homeserver);
1.943     raeburn  1450:             } elsif ($check eq 'email') {
                   1451:                 $response=&reply('instemailrules:'.&escape($udom),
                   1452:                                  $homeserver);
1.923     raeburn  1453:             } else {
                   1454:                 $response=&reply('instuserrules:'.&escape($udom),
                   1455:                                  $homeserver);
                   1456:             }
1.912     raeburn  1457:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1458:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1459:                 ($response ne 'no_such_host')) {
                   1460:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1461:                 my @pairs=split(/\&/,$hashitems);
                   1462:                 foreach my $item (@pairs) {
                   1463:                     my ($key,$value)=split(/=/,$item,2);
                   1464:                     $key = &unescape($key);
                   1465:                     next if ($key =~ /^error: 2 /);
                   1466:                     $ruleshash{$key}=&thaw_unescape($value);
                   1467:                 }
                   1468:                 my @esc_order = split(/\&/,$orderitems);
                   1469:                 foreach my $item (@esc_order) {
                   1470:                     push(@ruleorder,&unescape($item));
                   1471:                 }
                   1472:             }
                   1473:         }
                   1474:     }
                   1475:     return (\%ruleshash,\@ruleorder);
                   1476: }
                   1477: 
1.976     raeburn  1478: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1479: 
                   1480: sub get_domain_defaults {
                   1481:     my ($domain) = @_;
                   1482:     my $cachetime = 60*60*24;
                   1483:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1484:     if (defined($cached)) {
                   1485:         if (ref($result) eq 'HASH') {
                   1486:             return %{$result};
                   1487:         }
                   1488:     }
                   1489:     my %domdefaults;
                   1490:     my %domconfig =
1.989     raeburn  1491:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1492:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1493:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1494:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1495:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1496:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1497:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1498:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1499:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1500:     } else {
                   1501:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1502:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1503:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1504:     }
1.976     raeburn  1505:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1506:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1507:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1508:         } else {
                   1509:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1510:         } 
                   1511:         my @usertools = ('aboutme','blog','portfolio');
                   1512:         foreach my $item (@usertools) {
                   1513:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1514:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1515:             }
                   1516:         }
                   1517:     }
1.985     raeburn  1518:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1519:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1520:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1521:         }
                   1522:     }
1.989     raeburn  1523:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1524:         foreach my $item ('inststatustypes','inststatusorder') {
                   1525:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1526:         }
                   1527:     }
1.1047    raeburn  1528:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1529:         foreach my $item ('canuse_pdfforms') {
                   1530:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1531:         }
                   1532:     }
1.1056.4.3  raeburn  1533:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1534:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1535:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1536:         }
                   1537:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1538:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1539:         }
                   1540:     }
1.943     raeburn  1541:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1542:                                   $cachetime);
                   1543:     return %domdefaults;
                   1544: }
                   1545: 
1.344     www      1546: # --------------------------------------------------- Assign a key to a student
                   1547: 
                   1548: sub assign_access_key {
1.364     www      1549: #
                   1550: # a valid key looks like uname:udom#comments
                   1551: # comments are being appended
                   1552: #
1.498     www      1553:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1554:     $kdom=
1.620     albertel 1555:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1556:     $knum=
1.620     albertel 1557:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1558:     $cdom=
1.620     albertel 1559:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1560:     $cnum=
1.620     albertel 1561:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1562:     $udom=$env{'user.name'} unless (defined($udom));
                   1563:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1564:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1565:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1566:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1567:                                                   # assigned to this person
                   1568:                                                   # - this should not happen,
1.345     www      1569:                                                   # unless something went wrong
                   1570:                                                   # the first time around
                   1571: # ready to assign
1.364     www      1572:         $logentry=$1.'; '.$logentry;
1.496     www      1573:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1574:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1575: # key now belongs to user
1.346     www      1576: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1577:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1578:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1579:                 return 'ok';
                   1580:             } else {
                   1581:                 return 
                   1582:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1583: 	    }
                   1584:         } else {
                   1585:             return 'error: Could not assign key, try again later.';
                   1586:         }
1.364     www      1587:     } elsif (!$existing{$ckey}) {
1.345     www      1588: # the key does not exist
                   1589: 	return 'error: The key does not exist';
                   1590:     } else {
                   1591: # the key is somebody else's
                   1592: 	return 'error: The key is already in use';
                   1593:     }
1.344     www      1594: }
                   1595: 
1.364     www      1596: # ------------------------------------------ put an additional comment on a key
                   1597: 
                   1598: sub comment_access_key {
                   1599: #
                   1600: # a valid key looks like uname:udom#comments
                   1601: # comments are being appended
                   1602: #
                   1603:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1604:     $cdom=
1.620     albertel 1605:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1606:     $cnum=
1.620     albertel 1607:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1608:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1609:     if ($existing{$ckey}) {
                   1610:         $existing{$ckey}.='; '.$logentry;
                   1611: # ready to assign
1.367     www      1612:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1613:                                                  $cdom,$cnum) eq 'ok') {
                   1614: 	    return 'ok';
                   1615:         } else {
                   1616: 	    return 'error: Count not store comment.';
                   1617:         }
                   1618:     } else {
                   1619: # the key does not exist
                   1620: 	return 'error: The key does not exist';
                   1621:     }
                   1622: }
                   1623: 
1.344     www      1624: # ------------------------------------------------------ Generate a set of keys
                   1625: 
                   1626: sub generate_access_keys {
1.364     www      1627:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1628:     $cdom=
1.620     albertel 1629:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1630:     $cnum=
1.620     albertel 1631:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1632:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1633:     unless (($cdom) && ($cnum)) { return 0; }
                   1634:     if ($number>10000) { return 0; }
                   1635:     sleep(2); # make sure don't get same seed twice
                   1636:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1637:     my $total=0;
                   1638:     for (my $i=1;$i<=$number;$i++) {
                   1639:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1640:                   sprintf("%lx",int(100000*rand)).'-'.
                   1641:                   sprintf("%lx",int(100000*rand));
                   1642:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1643:        $newkey=~s/0/h/g; # and also 0 and O
                   1644:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1645:        if ($existing{$newkey}) {
                   1646:            $i--;
                   1647:        } else {
1.364     www      1648: 	  if (&put('accesskeys',
                   1649:               { $newkey => '# generated '.localtime().
1.620     albertel 1650:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1651:                            '; '.$logentry },
                   1652: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1653:               $total++;
                   1654: 	  }
                   1655:        }
                   1656:     }
1.620     albertel 1657:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1658:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1659:     return $total;
                   1660: }
                   1661: 
                   1662: # ------------------------------------------------------- Validate an accesskey
                   1663: 
                   1664: sub validate_access_key {
                   1665:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1666:     $cdom=
1.620     albertel 1667:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1668:     $cnum=
1.620     albertel 1669:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1670:     $udom=$env{'user.domain'} unless (defined($udom));
                   1671:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1672:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1673:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1674: }
                   1675: 
                   1676: # ------------------------------------- Find the section of student in a course
1.652     albertel 1677: sub devalidate_getsection_cache {
                   1678:     my ($udom,$unam,$courseid)=@_;
                   1679:     my $hashid="$udom:$unam:$courseid";
                   1680:     &devalidate_cache_new('getsection',$hashid);
                   1681: }
1.298     matthew  1682: 
1.815     albertel 1683: sub courseid_to_courseurl {
                   1684:     my ($courseid) = @_;
                   1685:     #already url style courseid
                   1686:     return $courseid if ($courseid =~ m{^/});
                   1687: 
                   1688:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1689: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1690: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1691: 	return "/$cdom/$cnum";
                   1692:     }
                   1693: 
                   1694:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1695:     if (exists($courseinfo{'num'})) {
                   1696: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1697:     }
                   1698: 
                   1699:     return undef;
                   1700: }
                   1701: 
1.298     matthew  1702: sub getsection {
                   1703:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1704:     my $cachetime=1800;
1.551     albertel 1705: 
                   1706:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1707:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1708:     if (defined($cached)) { return $result; }
                   1709: 
1.298     matthew  1710:     my %Pending; 
                   1711:     my %Expired;
                   1712:     #
                   1713:     # Each role can either have not started yet (pending), be active, 
                   1714:     #    or have expired.
                   1715:     #
                   1716:     # If there is an active role, we are done.
                   1717:     #
                   1718:     # If there is more than one role which has not started yet, 
                   1719:     #     choose the one which will start sooner
                   1720:     # If there is one role which has not started yet, return it.
                   1721:     #
                   1722:     # If there is more than one expired role, choose the one which ended last.
                   1723:     # If there is a role which has expired, return it.
                   1724:     #
1.815     albertel 1725:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1726:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1727:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1728:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1729:         my $section=$1;
                   1730:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1731:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1732:         my $now=time;
1.548     albertel 1733:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1734:             $Expired{$end}=$section;
                   1735:             next;
                   1736:         }
1.548     albertel 1737:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1738:             $Pending{$start}=$section;
                   1739:             next;
                   1740:         }
1.599     albertel 1741:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1742:     }
                   1743:     #
                   1744:     # Presumedly there will be few matching roles from the above
                   1745:     # loop and the sorting time will be negligible.
                   1746:     if (scalar(keys(%Pending))) {
                   1747:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1748:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1749:     } 
                   1750:     if (scalar(keys(%Expired))) {
                   1751:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1752:         my $time = pop(@sorted);
1.599     albertel 1753:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1754:     }
1.599     albertel 1755:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1756: }
1.70      www      1757: 
1.599     albertel 1758: sub save_cache {
                   1759:     &purge_remembered();
1.722     albertel 1760:     #&Apache::loncommon::validate_page();
1.620     albertel 1761:     undef(%env);
1.780     albertel 1762:     undef($env_loaded);
1.599     albertel 1763: }
1.452     albertel 1764: 
1.599     albertel 1765: my $to_remember=-1;
                   1766: my %remembered;
                   1767: my %accessed;
                   1768: my $kicks=0;
                   1769: my $hits=0;
1.849     albertel 1770: sub make_key {
                   1771:     my ($name,$id) = @_;
1.872     albertel 1772:     if (length($id) > 65 
                   1773: 	&& length(&escape($id)) > 200) {
                   1774: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1775:     }
1.849     albertel 1776:     return &escape($name.':'.$id);
                   1777: }
                   1778: 
1.599     albertel 1779: sub devalidate_cache_new {
                   1780:     my ($name,$id,$debug) = @_;
                   1781:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1782:     $id=&make_key($name,$id);
1.599     albertel 1783:     $memcache->delete($id);
                   1784:     delete($remembered{$id});
                   1785:     delete($accessed{$id});
                   1786: }
                   1787: 
                   1788: sub is_cached_new {
                   1789:     my ($name,$id,$debug) = @_;
1.849     albertel 1790:     $id=&make_key($name,$id);
1.599     albertel 1791:     if (exists($remembered{$id})) {
                   1792: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1793: 	$accessed{$id}=[&gettimeofday()];
                   1794: 	$hits++;
                   1795: 	return ($remembered{$id},1);
                   1796:     }
                   1797:     my $value = $memcache->get($id);
                   1798:     if (!(defined($value))) {
                   1799: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1800: 	return (undef,undef);
1.416     albertel 1801:     }
1.599     albertel 1802:     if ($value eq '__undef__') {
                   1803: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1804: 	$value=undef;
                   1805:     }
                   1806:     &make_room($id,$value,$debug);
                   1807:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1808:     return ($value,1);
                   1809: }
                   1810: 
                   1811: sub do_cache_new {
                   1812:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1813:     $id=&make_key($name,$id);
1.599     albertel 1814:     my $setvalue=$value;
                   1815:     if (!defined($setvalue)) {
                   1816: 	$setvalue='__undef__';
                   1817:     }
1.623     albertel 1818:     if (!defined($time) ) {
                   1819: 	$time=600;
                   1820:     }
1.599     albertel 1821:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1822:     my $result = $memcache->set($id,$setvalue,$time);
                   1823:     if (! $result) {
1.872     albertel 1824: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1825: 	$memcache->disconnect_all();
1.872     albertel 1826:     }
1.600     albertel 1827:     # need to make a copy of $value
1.919     albertel 1828:     &make_room($id,$value,$debug);
1.599     albertel 1829:     return $value;
                   1830: }
                   1831: 
                   1832: sub make_room {
                   1833:     my ($id,$value,$debug)=@_;
1.919     albertel 1834: 
                   1835:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1836:                                     : $value;
1.599     albertel 1837:     if ($to_remember<0) { return; }
                   1838:     $accessed{$id}=[&gettimeofday()];
                   1839:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1840:     my $to_kick;
                   1841:     my $max_time=0;
                   1842:     foreach my $other (keys(%accessed)) {
                   1843: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1844: 	    $to_kick=$other;
                   1845: 	    $max_time=&tv_interval($accessed{$other});
                   1846: 	}
                   1847:     }
                   1848:     delete($remembered{$to_kick});
                   1849:     delete($accessed{$to_kick});
                   1850:     $kicks++;
                   1851:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1852:     return;
                   1853: }
                   1854: 
1.599     albertel 1855: sub purge_remembered {
1.604     albertel 1856:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1857:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1858:     undef(%remembered);
                   1859:     undef(%accessed);
1.428     albertel 1860: }
1.70      www      1861: # ------------------------------------- Read an entry from a user's environment
                   1862: 
                   1863: sub userenvironment {
                   1864:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1865:     my $items;
                   1866:     foreach my $item (@what) {
                   1867:         $items.=&escape($item).'&';
                   1868:     }
                   1869:     $items=~s/\&$//;
1.70      www      1870:     my %returnhash=();
1.1009    raeburn  1871:     my $uhome = &homeserver($unam,$udom);
                   1872:     unless ($uhome eq 'no_host') {
                   1873:         my @answer=split(/\&/, 
                   1874:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1875:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1876:             return %returnhash;
                   1877:         }
1.1009    raeburn  1878:         my $i;
                   1879:         for ($i=0;$i<=$#what;$i++) {
                   1880: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1881:         }
1.70      www      1882:     }
                   1883:     return %returnhash;
1.1       albertel 1884: }
                   1885: 
1.617     albertel 1886: # ---------------------------------------------------------- Get a studentphoto
                   1887: sub studentphoto {
                   1888:     my ($udom,$unam,$ext) = @_;
                   1889:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1890:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1891:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1892:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1893:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1894:             } else {
                   1895:                 my ($result,$perm_reqd)=
1.707     albertel 1896: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1897:                 if ($result eq 'ok') {
                   1898:                     if (!($perm_reqd eq 'yes')) {
                   1899:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1900:                     }
                   1901:                 }
                   1902:             }
                   1903:         }
                   1904:     } else {
                   1905:         my ($result,$perm_reqd) = 
1.707     albertel 1906: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1907:         if ($result eq 'ok') {
                   1908:             if (!($perm_reqd eq 'yes')) {
                   1909:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1910:             }
                   1911:         }
                   1912:     }
                   1913:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1914: }
                   1915: 
                   1916: sub retrievestudentphoto {
                   1917:     my ($udom,$unam,$ext,$type) = @_;
                   1918:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1919:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1920:     if ($ret eq 'ok') {
                   1921:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1922:         if ($type eq 'thumbnail') {
                   1923:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1924:         }
                   1925:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1926:         return $tokenurl;
                   1927:     } else {
                   1928:         if ($type eq 'thumbnail') {
                   1929:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1930:         } else { 
                   1931:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1932:         }
1.617     albertel 1933:     }
                   1934: }
                   1935: 
1.263     www      1936: # -------------------------------------------------------------------- New chat
                   1937: 
                   1938: sub chatsend {
1.724     raeburn  1939:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1940:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1941:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1942:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1943:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1944: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1945: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1946: }
                   1947: 
                   1948: # ------------------------------------------ Find current version of a resource
                   1949: 
                   1950: sub getversion {
                   1951:     my $fname=&clutter(shift);
                   1952:     unless ($fname=~/^\/res\//) { return -1; }
                   1953:     return &currentversion(&filelocation('',$fname));
                   1954: }
                   1955: 
                   1956: sub currentversion {
                   1957:     my $fname=shift;
1.599     albertel 1958:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1959:     if (defined($cached)) { return $result; }
1.292     www      1960:     my $author=$fname;
                   1961:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1962:     my ($udom,$uname)=split(/\//,$author);
                   1963:     my $home=homeserver($uname,$udom);
                   1964:     if ($home eq 'no_host') { 
                   1965:         return -1; 
                   1966:     }
                   1967:     my $answer=reply("currentversion:$fname",$home);
                   1968:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1969: 	return -1;
                   1970:     }
1.599     albertel 1971:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1972: }
                   1973: 
1.1       albertel 1974: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1975: 
1.1       albertel 1976: sub subscribe {
                   1977:     my $fname=shift;
1.761     raeburn  1978:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1979:     $fname=~s/[\n\r]//g;
1.1       albertel 1980:     my $author=$fname;
                   1981:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1982:     my ($udom,$uname)=split(/\//,$author);
                   1983:     my $home=homeserver($uname,$udom);
1.335     albertel 1984:     if ($home eq 'no_host') {
                   1985:         return 'not_found';
1.1       albertel 1986:     }
                   1987:     my $answer=reply("sub:$fname",$home);
1.64      www      1988:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1989: 	$answer.=' by '.$home;
                   1990:     }
1.1       albertel 1991:     return $answer;
                   1992: }
                   1993:     
1.8       www      1994: # -------------------------------------------------------------- Replicate file
                   1995: 
                   1996: sub repcopy {
                   1997:     my $filename=shift;
1.23      www      1998:     $filename=~s/\/+/\//g;
1.607     raeburn  1999:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2000:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2001:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2002: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2003: 	return &repcopy_userfile($filename);
                   2004:     }
1.532     albertel 2005:     $filename=~s/[\n\r]//g;
1.8       www      2006:     my $transname="$filename.in.transfer";
1.828     www      2007: # FIXME: this should flock
1.607     raeburn  2008:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2009:     my $remoteurl=subscribe($filename);
1.64      www      2010:     if ($remoteurl =~ /^con_lost by/) {
                   2011: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2012:            return 'unavailable';
1.8       www      2013:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2014: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2015: 	   return 'not_found';
1.64      www      2016:     } elsif ($remoteurl =~ /^rejected by/) {
                   2017: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2018:            return 'forbidden';
1.20      www      2019:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2020:            return 'ok';
1.8       www      2021:     } else {
1.290     www      2022:         my $author=$filename;
                   2023:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2024:         my ($udom,$uname)=split(/\//,$author);
                   2025:         my $home=homeserver($uname,$udom);
                   2026:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2027:            my @parts=split(/\//,$filename);
                   2028:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2029:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2030:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2031: 	       return 'bad_request';
1.8       www      2032:            }
                   2033:            my $count;
                   2034:            for ($count=5;$count<$#parts;$count++) {
                   2035:                $path.="/$parts[$count]";
                   2036:                if ((-e $path)!=1) {
                   2037: 		   mkdir($path,0777);
                   2038:                }
                   2039:            }
                   2040:            my $ua=new LWP::UserAgent;
                   2041:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2042:            my $response=$ua->request($request,$transname);
                   2043:            if ($response->is_error()) {
                   2044: 	       unlink($transname);
                   2045:                my $message=$response->status_line;
1.672     albertel 2046:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2047:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2048:                return 'unavailable';
1.8       www      2049:            } else {
1.16      www      2050: 	       if ($remoteurl!~/\.meta$/) {
                   2051:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2052:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2053:                   if ($mresponse->is_error()) {
                   2054: 		      unlink($filename.'.meta');
                   2055:                       &logthis(
1.672     albertel 2056:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2057:                   }
                   2058: 	       }
1.8       www      2059:                rename($transname,$filename);
1.607     raeburn  2060:                return 'ok';
1.8       www      2061:            }
1.290     www      2062:        }
1.8       www      2063:     }
1.330     www      2064: }
                   2065: 
                   2066: # ------------------------------------------------ Get server side include body
                   2067: sub ssi_body {
1.381     albertel 2068:     my ($filelink,%form)=@_;
1.606     matthew  2069:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2070:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2071:     }
1.953     www      2072:     my $output='';
                   2073:     my $response;
1.980     raeburn  2074:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2075:        ($output,$response)=&externalssi($filelink);
1.953     www      2076:     } else {
1.1004    droeschl 2077:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2078:        $filelink .= 'inhibitmenu=yes';
1.953     www      2079:        ($output,$response)=&ssi($filelink,%form);
                   2080:     }
1.778     albertel 2081:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2082:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2083:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2084:     if (wantarray) {
                   2085:         return ($output, $response);
                   2086:     } else {
                   2087:         return $output;
                   2088:     }
1.8       www      2089: }
                   2090: 
1.15      www      2091: # --------------------------------------------------------- Server Side Include
                   2092: 
1.782     albertel 2093: sub absolute_url {
                   2094:     my ($host_name) = @_;
                   2095:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2096:     if ($host_name eq '') {
                   2097: 	$host_name = $ENV{'SERVER_NAME'};
                   2098:     }
                   2099:     return $protocol.$host_name;
                   2100: }
                   2101: 
1.942     foxr     2102: #
                   2103: #   Server side include.
                   2104: # Parameters:
                   2105: #  fn     Possibly encrypted resource name/id.
                   2106: #  form   Hash that describes how the rendering should be done
                   2107: #         and other things.
1.944     foxr     2108: # Returns:
1.950     raeburn  2109: #   Scalar context: The content of the response.
                   2110: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2111: #     
1.15      www      2112: sub ssi {
                   2113: 
1.944     foxr     2114:     my ($fn,%form)=@_;
1.15      www      2115:     my $ua=new LWP::UserAgent;
1.23      www      2116:     my $request;
1.711     albertel 2117: 
                   2118:     $form{'no_update_last_known'}=1;
1.895     albertel 2119:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2120:     if (%form) {
1.782     albertel 2121:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2122:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2123:     } else {
1.782     albertel 2124:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2125:     }
                   2126: 
1.15      www      2127:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2128:     my $response=$ua->request($request);
                   2129: 
1.944     foxr     2130:     if (wantarray) {
                   2131: 	return ($response->content, $response);
                   2132:     } else {
                   2133: 	return $response->content;
1.942     foxr     2134:     }
1.324     www      2135: }
                   2136: 
                   2137: sub externalssi {
                   2138:     my ($url)=@_;
                   2139:     my $ua=new LWP::UserAgent;
                   2140:     my $request=new HTTP::Request('GET',$url);
                   2141:     my $response=$ua->request($request);
1.954     raeburn  2142:     if (wantarray) {
                   2143:         return ($response->content, $response);
                   2144:     } else {
                   2145:         return $response->content;
                   2146:     }
1.15      www      2147: }
1.254     www      2148: 
1.492     albertel 2149: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2150: 
                   2151: sub allowuploaded {
                   2152:     my ($srcurl,$url)=@_;
                   2153:     $url=&clutter(&declutter($url));
                   2154:     my $dir=$url;
                   2155:     $dir=~s/\/[^\/]+$//;
                   2156:     my %httpref=();
                   2157:     my $httpurl=&hreflocation('',$url);
                   2158:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2159:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2160: }
1.477     raeburn  2161: 
1.478     albertel 2162: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2163: # input: action, courseID, current domain, intended
1.637     raeburn  2164: #        path to file, source of file, instruction to parse file for objects,
                   2165: #        ref to hash for embedded objects,
                   2166: #        ref to hash for codebase of java objects.
                   2167: #
1.485     raeburn  2168: # output: url to file (if action was uploaddoc), 
                   2169: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2170: #
1.478     albertel 2171: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2172: # course.
1.477     raeburn  2173: #
1.478     albertel 2174: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2175: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2176: #          course's home server.
1.477     raeburn  2177: #
1.478     albertel 2178: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2179: #          be copied from $source (current location) to 
                   2180: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2181: #         and will then be copied to
                   2182: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2183: #         course's home server.
1.485     raeburn  2184: #
1.481     raeburn  2185: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2186: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2187: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2188: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2189: #         in course's home server.
1.637     raeburn  2190: #
1.477     raeburn  2191: 
                   2192: sub process_coursefile {
1.638     albertel 2193:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2194:     my $fetchresult;
1.638     albertel 2195:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2196:     if ($action eq 'propagate') {
1.638     albertel 2197:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2198: 			     $home);
1.481     raeburn  2199:     } else {
1.477     raeburn  2200:         my $fpath = '';
                   2201:         my $fname = $file;
1.478     albertel 2202:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2203:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2204:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2205:         if ($action eq 'copy') {
                   2206:             if ($source eq '') {
                   2207:                 $fetchresult = 'no source file';
                   2208:                 return $fetchresult;
                   2209:             } else {
                   2210:                 my $destination = $filepath.'/'.$fname;
                   2211:                 rename($source,$destination);
                   2212:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2213:                                  $home);
1.481     raeburn  2214:             }
                   2215:         } elsif ($action eq 'uploaddoc') {
                   2216:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2217:             print $fh $env{'form.'.$source};
1.481     raeburn  2218:             close($fh);
1.637     raeburn  2219:             if ($parser eq 'parse') {
1.1024    raeburn  2220:                 my $mm = new File::MMagic;
                   2221:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2222:                 if ($mime_type eq 'text/html') {
                   2223:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2224:                     unless ($parse_result eq 'ok') {
                   2225:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2226:                     }
1.637     raeburn  2227:                 }
                   2228:             }
1.477     raeburn  2229:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2230:                                  $home);
1.481     raeburn  2231:             if ($fetchresult eq 'ok') {
                   2232:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2233:             } else {
                   2234:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2235:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2236:                 return '/adm/notfound.html';
                   2237:             }
1.477     raeburn  2238:         }
                   2239:     }
1.485     raeburn  2240:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2241:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2242:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2243:     }
                   2244:     return $fetchresult;
                   2245: }
                   2246: 
1.637     raeburn  2247: sub build_filepath {
                   2248:     my ($fpath) = @_;
                   2249:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2250:     unless ($fpath eq '') {
                   2251:         my @parts=split('/',$fpath);
                   2252:         foreach my $part (@parts) {
                   2253:             $filepath.= '/'.$part;
                   2254:             if ((-e $filepath)!=1) {
                   2255:                 mkdir($filepath,0777);
                   2256:             }
                   2257:         }
                   2258:     }
                   2259:     return $filepath;
                   2260: }
                   2261: 
                   2262: sub store_edited_file {
1.638     albertel 2263:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2264:     my $file = $primary_url;
                   2265:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2266:     my $fpath = '';
                   2267:     my $fname = $file;
                   2268:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2269:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2270:     my $filepath = &build_filepath($fpath);
                   2271:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2272:     print $fh $content;
                   2273:     close($fh);
1.638     albertel 2274:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2275:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2276: 			  $home);
1.637     raeburn  2277:     if ($$fetchresult eq 'ok') {
                   2278:         return '/uploaded/'.$fpath.'/'.$fname;
                   2279:     } else {
1.638     albertel 2280:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2281: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2282:         return '/adm/notfound.html';
                   2283:     }
                   2284: }
                   2285: 
1.531     albertel 2286: sub clean_filename {
1.831     albertel 2287:     my ($fname,$args)=@_;
1.315     www      2288: # Replace Windows backslashes by forward slashes
1.257     www      2289:     $fname=~s/\\/\//g;
1.831     albertel 2290:     if (!$args->{'keep_path'}) {
                   2291:         # Get rid of everything but the actual filename
                   2292: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2293:     }
1.315     www      2294: # Replace spaces by underscores
                   2295:     $fname=~s/\s+/\_/g;
                   2296: # Replace all other weird characters by nothing
1.831     albertel 2297:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2298: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2299: # numbers
                   2300:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2301:     return $fname;
                   2302: }
1.1051    raeburn  2303: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2304: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2305: # image with the same aspect ratio as the original, but with dimensions which do 
                   2306: # not exceed $resizewidth and $resizeheight.
                   2307:  
1.984     neumanie 2308: sub resizeImage {
1.1051    raeburn  2309:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2310:     my $ima = Image::Magick->new;
                   2311:     my $resized;
                   2312:     if (-e $img_path) {
                   2313:         $ima->Read($img_path);
                   2314:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2315:             my $width = $ima->Get('width');
                   2316:             my $height = $ima->Get('height');
                   2317:             if ($width > $resizewidth) {
                   2318: 	        my $factor = $width/$resizewidth;
                   2319:                 my $newheight = $height/$factor;
                   2320:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2321:                 $resized = 1;
                   2322:             }
                   2323:         }
                   2324:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2325:             my $width = $ima->Get('width');
                   2326:             my $height = $ima->Get('height');
                   2327:             if ($height > $resizeheight) {
                   2328:                 my $factor = $height/$resizeheight;
                   2329:                 my $newwidth = $width/$factor;
                   2330:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2331:                 $resized = 1;
                   2332:             }
                   2333:         }
                   2334:         if ($resized) {
                   2335:             $ima->Write($img_path);
                   2336:         }
                   2337:     }
                   2338:     return;
1.977     amueller 2339: }
                   2340: 
1.608     albertel 2341: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2342: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2343: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2344: #        $coursedoc - if true up to the current course
                   2345: #                     if false
                   2346: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2347: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2348: #        $allfiles - reference to hash for embedded objects
                   2349: #        $codebase - reference to hash for codebase of java objects
                   2350: #        $desuname - username for permanent storage of uploaded file
                   2351: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2352: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2353: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2354: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2355: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2356: # 
1.686     albertel 2357: # output: url of file in userspace, or error: <message> 
                   2358: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2359: 
1.531     albertel 2360: sub userfileupload {
1.860     raeburn  2361:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2362:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2363:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2364:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2365:     $fname=&clean_filename($fname);
1.315     www      2366: # See if there is anything left
1.257     www      2367:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2368:     chop($env{'form.'.$formname});
1.523     raeburn  2369:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2370:         my $now = time;
                   2371:         my $filepath = 'tmp/helprequests/'.$now;
                   2372:         my @parts=split(/\//,$filepath);
                   2373:         my $fullpath = $perlvar{'lonDaemons'};
                   2374:         for (my $i=0;$i<@parts;$i++) {
                   2375:             $fullpath .= '/'.$parts[$i];
                   2376:             if ((-e $fullpath)!=1) {
                   2377:                 mkdir($fullpath,0777);
                   2378:             }
                   2379:         }
                   2380:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2381:         print $fh $env{'form.'.$formname};
1.523     raeburn  2382:         close($fh);
1.741     raeburn  2383:         return $fullpath.'/'.$fname;
                   2384:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2385:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2386:                        '_'.$env{'user.domain'}.'/pending';
                   2387:         my @parts=split(/\//,$filepath);
                   2388:         my $fullpath = $perlvar{'lonDaemons'};
                   2389:         for (my $i=0;$i<@parts;$i++) {
                   2390:             $fullpath .= '/'.$parts[$i];
                   2391:             if ((-e $fullpath)!=1) {
                   2392:                 mkdir($fullpath,0777);
                   2393:             }
                   2394:         }
                   2395:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2396:         print $fh $env{'form.'.$formname};
                   2397:         close($fh);
                   2398:         return $fullpath.'/'.$fname;
1.523     raeburn  2399:     }
1.995     raeburn  2400:     if ($subdir eq 'scantron') {
                   2401:         $fname = 'scantron_orig_'.$fname;
                   2402:     } else {   
1.258     www      2403: # Create the directory if not present
1.995     raeburn  2404:         $fname="$subdir/$fname";
                   2405:     }
1.259     www      2406:     if ($coursedoc) {
1.638     albertel 2407: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2408: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2409:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2410:             return &finishuserfileupload($docuname,$docudom,
                   2411: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2412: 					 $codebase,$thumbwidth,$thumbheight,
                   2413:                                          $resizewidth,$resizeheight);
1.481     raeburn  2414:         } else {
1.620     albertel 2415:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2416:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2417: 				       $fname,$formname,$parser,
                   2418: 				       $allfiles,$codebase);
1.481     raeburn  2419:         }
1.719     banghart 2420:     } elsif (defined($destuname)) {
                   2421:         my $docuname=$destuname;
                   2422:         my $docudom=$destudom;
1.860     raeburn  2423: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2424: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2425:                                      $thumbwidth,$thumbheight,
                   2426:                                      $resizewidth,$resizeheight);
1.719     banghart 2427:         
1.259     www      2428:     } else {
1.638     albertel 2429:         my $docuname=$env{'user.name'};
                   2430:         my $docudom=$env{'user.domain'};
1.714     raeburn  2431:         if (exists($env{'form.group'})) {
                   2432:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2433:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2434:         }
1.860     raeburn  2435: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2436: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2437:                                      $thumbwidth,$thumbheight,
                   2438:                                      $resizewidth,$resizeheight);
1.259     www      2439:     }
1.271     www      2440: }
                   2441: 
                   2442: sub finishuserfileupload {
1.860     raeburn  2443:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051    raeburn  2444:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477     raeburn  2445:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2446:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2447:   
1.860     raeburn  2448:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2449:     $file=$fname;
                   2450:     if ($fname=~m|/|) {
                   2451:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2452: 	$path.=$fnamepath.'/';
                   2453:     }
1.259     www      2454:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2455:     my $count;
                   2456:     for ($count=4;$count<=$#parts;$count++) {
                   2457:         $filepath.="/$parts[$count]";
                   2458:         if ((-e $filepath)!=1) {
                   2459: 	    mkdir($filepath,0777);
                   2460:         }
                   2461:     }
1.984     neumanie 2462: 
1.258     www      2463: # Save the file
                   2464:     {
1.701     albertel 2465: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2466: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2467: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2468: 	    return '/adm/notfound.html';
                   2469: 	}
                   2470: 	if (!print FH ($env{'form.'.$formname})) {
                   2471: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2472: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2473: 	    return '/adm/notfound.html';
                   2474: 	}
1.570     albertel 2475: 	close(FH);
1.1051    raeburn  2476:         if ($resizewidth && $resizeheight) {
                   2477:             my $mm = new File::MMagic;
                   2478:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2479:             if ($mime_type =~ m{^image/}) {
                   2480: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2481:             }  
1.977     amueller 2482: 	}
1.258     www      2483:     }
1.637     raeburn  2484:     if ($parser eq 'parse') {
1.1024    raeburn  2485:         my $mm = new File::MMagic;
                   2486:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2487:         if ($mime_type eq 'text/html') {
                   2488:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2489:                                                        $allfiles,$codebase);
                   2490:             unless ($parse_result eq 'ok') {
                   2491:                 &logthis('Failed to parse '.$filepath.$file.
                   2492: 	   	         ' for embedded media: '.$parse_result); 
                   2493:             }
1.637     raeburn  2494:         }
                   2495:     }
1.860     raeburn  2496:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2497:         my $input = $filepath.'/'.$file;
                   2498:         my $output = $filepath.'/'.'tn-'.$file;
                   2499:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2500:         system("convert -sample $thumbsize $input $output");
                   2501:         if (-e $filepath.'/'.'tn-'.$file) {
                   2502:             $fetchthumb  = 1; 
                   2503:         }
                   2504:     }
1.858     raeburn  2505:  
1.259     www      2506: # Notify homeserver to grep it
                   2507: #
1.984     neumanie 2508:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2509:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2510:     if ($fetchresult eq 'ok') {
1.860     raeburn  2511:         if ($fetchthumb) {
                   2512:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2513:             if ($thumbresult ne 'ok') {
                   2514:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2515:                          $docuhome.': '.$thumbresult);
                   2516:             }
                   2517:         }
1.259     www      2518: #
1.258     www      2519: # Return the URL to it
1.494     albertel 2520:         return '/uploaded/'.$path.$file;
1.263     www      2521:     } else {
1.494     albertel 2522:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2523: 		 ': '.$fetchresult);
1.263     www      2524:         return '/adm/notfound.html';
1.858     raeburn  2525:     }
1.493     albertel 2526: }
                   2527: 
1.637     raeburn  2528: sub extract_embedded_items {
1.961     raeburn  2529:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2530:     my @state = ();
                   2531:     my %javafiles = (
                   2532:                       codebase => '',
                   2533:                       code => '',
                   2534:                       archive => ''
                   2535:                     );
                   2536:     my %mediafiles = (
                   2537:                       src => '',
                   2538:                       movie => '',
                   2539:                      );
1.648     raeburn  2540:     my $p;
                   2541:     if ($content) {
                   2542:         $p = HTML::LCParser->new($content);
                   2543:     } else {
1.961     raeburn  2544:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2545:     }
1.641     albertel 2546:     while (my $t=$p->get_token()) {
1.640     albertel 2547: 	if ($t->[0] eq 'S') {
                   2548: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2549: 	    push(@state, $tagname);
1.648     raeburn  2550:             if (lc($tagname) eq 'allow') {
                   2551:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2552:             }
1.640     albertel 2553: 	    if (lc($tagname) eq 'img') {
                   2554: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2555: 	    }
1.886     albertel 2556: 	    if (lc($tagname) eq 'a') {
                   2557: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2558: 	    }
1.645     raeburn  2559:             if (lc($tagname) eq 'script') {
                   2560:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2561:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2562:                 } else {
                   2563:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2564:                 }
                   2565:             }
                   2566:             if (lc($tagname) eq 'link') {
                   2567:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2568:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2569:                 }
                   2570:             }
1.640     albertel 2571: 	    if (lc($tagname) eq 'object' ||
                   2572: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2573: 		foreach my $item (keys(%javafiles)) {
                   2574: 		    $javafiles{$item} = '';
                   2575: 		}
                   2576: 	    }
                   2577: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2578: 		my $name = lc($attr->{'name'});
                   2579: 		foreach my $item (keys(%javafiles)) {
                   2580: 		    if ($name eq $item) {
                   2581: 			$javafiles{$item} = $attr->{'value'};
                   2582: 			last;
                   2583: 		    }
                   2584: 		}
                   2585: 		foreach my $item (keys(%mediafiles)) {
                   2586: 		    if ($name eq $item) {
                   2587: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2588: 			last;
                   2589: 		    }
                   2590: 		}
                   2591: 	    }
                   2592: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2593: 		foreach my $item (keys(%javafiles)) {
                   2594: 		    if ($attr->{$item}) {
                   2595: 			$javafiles{$item} = $attr->{$item};
                   2596: 			last;
                   2597: 		    }
                   2598: 		}
                   2599: 		foreach my $item (keys(%mediafiles)) {
                   2600: 		    if ($attr->{$item}) {
                   2601: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2602: 			last;
                   2603: 		    }
                   2604: 		}
                   2605: 	    }
                   2606: 	} elsif ($t->[0] eq 'E') {
                   2607: 	    my ($tagname) = ($t->[1]);
                   2608: 	    if ($javafiles{'codebase'} ne '') {
                   2609: 		$javafiles{'codebase'} .= '/';
                   2610: 	    }  
                   2611: 	    if (lc($tagname) eq 'applet' ||
                   2612: 		lc($tagname) eq 'object' ||
                   2613: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2614: 		) {
                   2615: 		foreach my $item (keys(%javafiles)) {
                   2616: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2617: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2618: 			&add_filetype($allfiles,$file,$item);
                   2619: 		    }
                   2620: 		}
                   2621: 	    } 
                   2622: 	    pop @state;
                   2623: 	}
                   2624:     }
1.637     raeburn  2625:     return 'ok';
                   2626: }
                   2627: 
1.639     albertel 2628: sub add_filetype {
                   2629:     my ($allfiles,$file,$type)=@_;
                   2630:     if (exists($allfiles->{$file})) {
                   2631: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2632: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2633: 	}
                   2634:     } else {
                   2635: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2636:     }
                   2637: }
                   2638: 
1.493     albertel 2639: sub removeuploadedurl {
1.984     neumanie 2640:     my ($url)=@_;	
                   2641:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2642:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2643: }
                   2644: 
                   2645: sub removeuserfile {
                   2646:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2647:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2648:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2649:     if ($result eq 'ok') {	
1.798     raeburn  2650:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2651:             my $metafile = $fname.'.meta';
                   2652:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2653: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2654:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2655:             my $sqlresult = 
1.823     albertel 2656:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2657:                                         'portfolio_metadata',$group,
                   2658:                                         'delete');
1.798     raeburn  2659:         }
                   2660:     }
                   2661:     return $result;
1.257     www      2662: }
1.15      www      2663: 
1.530     albertel 2664: sub mkdiruserfile {
                   2665:     my ($docuname,$docudom,$dir)=@_;
                   2666:     my $home=&homeserver($docuname,$docudom);
                   2667:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2668: }
                   2669: 
1.531     albertel 2670: sub renameuserfile {
                   2671:     my ($docuname,$docudom,$old,$new)=@_;
                   2672:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2673:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2674:                         &escape("$old").':'.&escape("$new"),$home);
                   2675:     if ($result eq 'ok') {
                   2676:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2677:             my $oldmeta = $old.'.meta';
                   2678:             my $newmeta = $new.'.meta';
                   2679:             my $metaresult = 
                   2680:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2681: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2682:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2683:             my $sqlresult = 
1.823     albertel 2684:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2685:                                         'portfolio_metadata',$group,
                   2686:                                         'delete');
1.798     raeburn  2687:         }
                   2688:     }
                   2689:     return $result;
1.531     albertel 2690: }
                   2691: 
1.14      www      2692: # ------------------------------------------------------------------------- Log
                   2693: 
                   2694: sub log {
                   2695:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2696:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2697: }
                   2698: 
                   2699: # ------------------------------------------------------------------ Course Log
1.352     www      2700: #
                   2701: # This routine flushes several buffers of non-mission-critical nature
                   2702: #
1.157     www      2703: 
                   2704: sub flushcourselogs {
1.352     www      2705:     &logthis('Flushing log buffers');
                   2706: #
                   2707: # course logs
                   2708: # This is a log of all transactions in a course, which can be used
                   2709: # for data mining purposes
                   2710: #
                   2711: # It also collects the courseid database, which lists last transaction
                   2712: # times and course titles for all courseids
                   2713: #
                   2714:     my %courseidbuffer=();
1.921     raeburn  2715:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2716:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2717: 		          &escape($courselogs{$crsid}),
                   2718: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2719: 	    delete $courselogs{$crsid};
                   2720:         } else {
                   2721:             &logthis('Failed to flush log buffer for '.$crsid);
                   2722:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2723:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2724:                         " exceeded maximum size, deleting.</font>");
                   2725:                delete $courselogs{$crsid};
                   2726:             }
1.352     www      2727:         }
1.920     raeburn  2728:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2729:             'description' => $coursedescrbuf{$crsid},
                   2730:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2731:             'type'        => $coursetypebuf{$crsid},
                   2732:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2733:         };
1.191     harris41 2734:     }
1.352     www      2735: #
                   2736: # Write course id database (reverse lookup) to homeserver of courses 
                   2737: # Is used in pickcourse
                   2738: #
1.840     albertel 2739:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2740:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2741:                                     $courseidbuffer{$crs_home},
                   2742:                                     $crs_home,'timeonly');
1.352     www      2743:     }
                   2744: #
                   2745: # File accesses
                   2746: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2747: #
1.449     matthew  2748:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2749:         if ($entry =~ /___count$/) {
                   2750:             my ($dom,$name);
1.807     albertel 2751:             ($dom,$name,undef)=
1.811     albertel 2752: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2753:             if (! defined($dom) || $dom eq '' || 
                   2754:                 ! defined($name) || $name eq '') {
1.620     albertel 2755:                 my $cid = $env{'request.course.id'};
                   2756:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2757:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2758:             }
1.450     matthew  2759:             my $value = $accesshash{$entry};
                   2760:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2761:             my %temphash=($url => $value);
1.449     matthew  2762:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2763:             if ($result eq 'ok') {
                   2764:                 delete $accesshash{$entry};
                   2765:             } elsif ($result eq 'unknown_cmd') {
                   2766:                 # Target server has old code running on it.
1.450     matthew  2767:                 my %temphash=($entry => $value);
1.449     matthew  2768:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2769:                     delete $accesshash{$entry};
                   2770:                 }
                   2771:             }
                   2772:         } else {
1.811     albertel 2773:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2774:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2775:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2776:                 delete $accesshash{$entry};
                   2777:             }
1.185     www      2778:         }
1.191     harris41 2779:     }
1.352     www      2780: #
                   2781: # Roles
                   2782: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2783: #
1.800     albertel 2784:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2785:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2786: 	    split(/\:/,$entry);
                   2787:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2788:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2789:                 $rudom,$runame) eq 'ok') {
                   2790: 	    delete $userrolehash{$entry};
                   2791:         }
                   2792:     }
1.662     raeburn  2793: #
                   2794: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2795: #
                   2796:     my %domrolebuffer = ();
1.1000    raeburn  2797:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2798:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2799:         if ($domrolebuffer{$rudom}) {
                   2800:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2801:                       '='.&escape($domainrolehash{$entry});
                   2802:         } else {
                   2803:             $domrolebuffer{$rudom}.=&escape($entry).
                   2804:                       '='.&escape($domainrolehash{$entry});
                   2805:         }
                   2806:         delete $domainrolehash{$entry};
                   2807:     }
                   2808:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2809: 	my %servers = &get_servers($dom,'library');
                   2810: 	foreach my $tryserver (keys(%servers)) {
                   2811: 	    unless (&reply('domroleput:'.$dom.':'.
                   2812: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2813: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2814: 	    }
1.662     raeburn  2815:         }
                   2816:     }
1.186     www      2817:     $dumpcount++;
1.157     www      2818: }
                   2819: 
                   2820: sub courselog {
                   2821:     my $what=shift;
1.158     www      2822:     $what=time.':'.$what;
1.620     albertel 2823:     unless ($env{'request.course.id'}) { return ''; }
                   2824:     $coursedombuf{$env{'request.course.id'}}=
                   2825:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2826:     $coursenumbuf{$env{'request.course.id'}}=
                   2827:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2828:     $coursehombuf{$env{'request.course.id'}}=
                   2829:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2830:     $coursedescrbuf{$env{'request.course.id'}}=
                   2831:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2832:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2833:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2834:     $courseownerbuf{$env{'request.course.id'}}=
                   2835:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2836:     $coursetypebuf{$env{'request.course.id'}}=
                   2837:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2838:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2839: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2840:     } else {
1.620     albertel 2841: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2842:     }
1.620     albertel 2843:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2844: 	&flushcourselogs();
                   2845:     }
1.158     www      2846: }
                   2847: 
                   2848: sub courseacclog {
                   2849:     my $fnsymb=shift;
1.620     albertel 2850:     unless ($env{'request.course.id'}) { return ''; }
                   2851:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2852:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2853:         $what.=':POST';
1.583     matthew  2854:         # FIXME: Probably ought to escape things....
1.800     albertel 2855: 	foreach my $key (keys(%env)) {
                   2856:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2857:                 my $formitem = $1;
                   2858:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2859:                     $what.=':'.$formitem.'='.$env{$key};
                   2860:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2861:                     $what.=':'.$formitem.'='.$env{$key};
                   2862:                 }
1.158     www      2863:             }
1.191     harris41 2864:         }
1.583     matthew  2865:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2866:         # FIXME: We should not be depending on a form parameter that someone
                   2867:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2868:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2869:             $what.= ':POST';
                   2870:             # FIXME: Probably ought to escape things....
                   2871:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2872:                                  'crsdiscuss') {
1.620     albertel 2873:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2874:             }
                   2875:         }
1.158     www      2876:     }
                   2877:     &courselog($what);
1.149     www      2878: }
                   2879: 
1.185     www      2880: sub countacc {
                   2881:     my $url=&declutter(shift);
1.458     matthew  2882:     return if (! defined($url) || $url eq '');
1.620     albertel 2883:     unless ($env{'request.course.id'}) { return ''; }
                   2884:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2885:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2886:     $accesshash{$key}++;
1.185     www      2887: }
1.349     www      2888: 
1.361     www      2889: sub linklog {
                   2890:     my ($from,$to)=@_;
                   2891:     $from=&declutter($from);
                   2892:     $to=&declutter($to);
                   2893:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2894:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2895: }
                   2896:   
1.349     www      2897: sub userrolelog {
                   2898:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2899:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2900:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2901:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2902:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2903:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2904:        $userrolehash
                   2905:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2906:                     =$tend.':'.$tstart;
1.662     raeburn  2907:     }
1.898     albertel 2908:     if (($env{'request.role'} =~ /dc\./) &&
                   2909: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2910: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2911: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2912:          ($trole=~/^co/))) {
1.898     albertel 2913:        $userrolehash
                   2914:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2915:                     =$tend.':'.$tstart;
                   2916:     }
1.662     raeburn  2917:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2918:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2919:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2920:         ($trole=~/^sc/)) {
                   2921:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2922:        $domainrolehash
                   2923:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2924:                     = $tend.':'.$tstart;
                   2925:     }
1.351     www      2926: }
                   2927: 
1.957     raeburn  2928: sub courserolelog {
                   2929:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2930:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2931:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2932:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2933:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2934:         ($trole eq 'co')) {
1.957     raeburn  2935:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2936:             my $cdom = $1;
                   2937:             my $cnum = $2;
                   2938:             my $sec = $3;
                   2939:             my $namespace = 'rolelog';
                   2940:             my %storehash = (
                   2941:                                role    => $trole,
                   2942:                                start   => $tstart,
                   2943:                                end     => $tend,
                   2944:                                selfenroll => $selfenroll,
                   2945:                                context    => $context,
                   2946:                             );
                   2947:             if ($trole eq 'gr') {
                   2948:                 $namespace = 'groupslog';
                   2949:                 $storehash{'group'} = $sec;
                   2950:             } else {
                   2951:                 $storehash{'section'} = $sec;
                   2952:             }
                   2953:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2954:             if (($trole ne 'st') || ($sec ne '')) {
                   2955:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2956:             }
1.957     raeburn  2957:         }
                   2958:     }
                   2959:     return;
                   2960: }
                   2961: 
1.351     www      2962: sub get_course_adv_roles {
1.948     raeburn  2963:     my ($cid,$codes) = @_;
1.620     albertel 2964:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2965:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2966:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2967:     my %nothide=();
1.800     albertel 2968:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2969:         if ($user !~ /:/) {
                   2970: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2971:         } else {
                   2972:             $nothide{$user}=1;
                   2973:         }
1.470     www      2974:     }
1.351     www      2975:     my %returnhash=();
                   2976:     my %dumphash=
                   2977:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2978:     my $now=time;
1.997     raeburn  2979:     my %privileged;
1.1000    raeburn  2980:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2981: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2982:         if (($tstart) && ($tstart<0)) { next; }
                   2983:         if (($tend) && ($tend<$now)) { next; }
                   2984:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2985:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2986: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2987:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2988:             my %dompersonnel =
1.998     raeburn  2989:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2990:             $privileged{$domain} = {};
                   2991:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2992:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2993:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2994:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2995:                         $privileged{$udom}{$uname} = 1;
                   2996:                     }
                   2997:                 }
                   2998:             }
                   2999:         }
                   3000:         if ((exists($privileged{$domain}{$username})) && 
                   3001:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3002: 	if ($role eq 'cr') { next; }
1.948     raeburn  3003:         if ($codes) {
                   3004:             if ($section) { $role .= ':'.$section; }
                   3005:             if ($returnhash{$role}) {
                   3006:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3007:             } else {
                   3008:                 $returnhash{$role}=$username.':'.$domain;
                   3009:             }
1.351     www      3010:         } else {
1.988     raeburn  3011:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3012:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3013:             if ($returnhash{$key}) {
                   3014: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3015:             } else {
                   3016:                 $returnhash{$key}=$username.':'.$domain;
                   3017:             }
1.351     www      3018:         }
1.948     raeburn  3019:     }
1.400     www      3020:     return %returnhash;
                   3021: }
                   3022: 
                   3023: sub get_my_roles {
1.937     raeburn  3024:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3025:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3026:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3027:     my (%dumphash,%nothide);
1.858     raeburn  3028:     if ($context eq 'userroles') { 
                   3029:         %dumphash = &dump('roles',$udom,$uname);
                   3030:     } else {
                   3031:         %dumphash=
1.400     www      3032:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3033:         if ($hidepriv) {
                   3034:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3035:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3036:                 if ($user !~ /:/) {
                   3037:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3038:                 } else {
                   3039:                     $nothide{$user} = 1;
                   3040:                 }
                   3041:             }
                   3042:         }
1.858     raeburn  3043:     }
1.400     www      3044:     my %returnhash=();
                   3045:     my $now=time;
1.999     raeburn  3046:     my %privileged;
1.800     albertel 3047:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3048:         my ($role,$tend,$tstart);
                   3049:         if ($context eq 'userroles') {
                   3050: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3051:         } else {
                   3052:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3053:         }
1.400     www      3054:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3055:         my $status = 'active';
1.939     raeburn  3056:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3057:             $status = 'previous';
                   3058:         } 
                   3059:         if (($tstart) && ($now<$tstart)) {
                   3060:             $status = 'future';
                   3061:         }
                   3062:         if (ref($types) eq 'ARRAY') {
                   3063:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3064:                 next;
                   3065:             } 
                   3066:         } else {
                   3067:             if ($status ne 'active') {
                   3068:                 next;
                   3069:             }
                   3070:         }
1.867     raeburn  3071:         my ($rolecode,$username,$domain,$section,$area);
                   3072:         if ($context eq 'userroles') {
                   3073:             ($area,$rolecode) = split(/_/,$entry);
                   3074:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3075:         } else {
                   3076:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3077:         }
1.832     raeburn  3078:         if (ref($roledoms) eq 'ARRAY') {
                   3079:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3080:                 next;
                   3081:             }
                   3082:         }
                   3083:         if (ref($roles) eq 'ARRAY') {
                   3084:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3085:                 if ($role =~ /^cr\//) {
                   3086:                     if (!grep(/^cr$/,@{$roles})) {
                   3087:                         next;
                   3088:                     }
                   3089:                 } else {
                   3090:                     next;
                   3091:                 }
1.832     raeburn  3092:             }
1.867     raeburn  3093:         }
1.937     raeburn  3094:         if ($hidepriv) {
1.999     raeburn  3095:             if ($context eq 'userroles') {
                   3096:                 if ((&privileged($username,$domain)) &&
                   3097:                     (!$nothide{$username.':'.$domain})) {
                   3098:                     next;
                   3099:                 }
                   3100:             } else {
                   3101:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3102:                     my %dompersonnel =
                   3103:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3104:                     $privileged{$domain} = {};
                   3105:                     if (keys(%dompersonnel)) {
                   3106:                         foreach my $server (keys(%dompersonnel)) {
                   3107:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3108:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3109:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3110:                                     $privileged{$udom}{$uname} = $trole;
                   3111:                                 }
                   3112:                             }
                   3113:                         }
                   3114:                     }
                   3115:                 }
                   3116:                 if (exists($privileged{$domain}{$username})) {
                   3117:                     if (!$nothide{$username.':'.$domain}) {
                   3118:                         next;
                   3119:                     }
                   3120:                 }
1.937     raeburn  3121:             }
                   3122:         }
1.933     raeburn  3123:         if ($withsec) {
                   3124:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3125:                 $tstart.':'.$tend;
                   3126:         } else {
                   3127:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3128:         }
1.832     raeburn  3129:     }
1.373     www      3130:     return %returnhash;
1.399     www      3131: }
                   3132: 
                   3133: # ----------------------------------------------------- Frontpage Announcements
                   3134: #
                   3135: #
                   3136: 
                   3137: sub postannounce {
                   3138:     my ($server,$text)=@_;
1.844     albertel 3139:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3140:     unless ($text=~/\w/) { $text=''; }
                   3141:     return &reply('setannounce:'.&escape($text),$server);
                   3142: }
                   3143: 
                   3144: sub getannounce {
1.448     albertel 3145: 
                   3146:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3147: 	my $announcement='';
1.800     albertel 3148: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3149: 	close($fh);
1.399     www      3150: 	if ($announcement=~/\w/) { 
                   3151: 	    return 
                   3152:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3153:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3154: 	} else {
                   3155: 	    return '';
                   3156: 	}
                   3157:     } else {
                   3158: 	return '';
                   3159:     }
1.351     www      3160: }
1.353     www      3161: 
                   3162: # ---------------------------------------------------------- Course ID routines
                   3163: # Deal with domain's nohist_courseid.db files
                   3164: #
                   3165: 
                   3166: sub courseidput {
1.921     raeburn  3167:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3168:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3169:     my $outcome;
                   3170:     if ($caller eq 'timeonly') {
                   3171:         my $cids = '';
                   3172:         foreach my $item (keys(%$storehash)) {
                   3173:             $cids.=&escape($item).'&';
                   3174:         }
                   3175:         $cids=~s/\&$//;
                   3176:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3177:                           $coursehome);       
                   3178:     } else {
                   3179:         my $items = '';
                   3180:         foreach my $item (keys(%$storehash)) {
                   3181:             $items.= &escape($item).'='.
                   3182:                      &freeze_escape($$storehash{$item}).'&';
                   3183:         }
                   3184:         $items=~s/\&$//;
                   3185:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3186:                           $coursehome);
1.918     raeburn  3187:     }
                   3188:     if ($outcome eq 'unknown_cmd') {
                   3189:         my $what;
                   3190:         foreach my $cid (keys(%$storehash)) {
                   3191:             $what .= &escape($cid).'=';
1.921     raeburn  3192:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3193:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3194:             }
                   3195:             $what =~ s/\:$/&/;
                   3196:         }
                   3197:         $what =~ s/\&$//;  
                   3198:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3199:     } else {
                   3200:         return $outcome;
                   3201:     }
1.353     www      3202: }
                   3203: 
                   3204: sub courseiddump {
1.921     raeburn  3205:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3206:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3207:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3208:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3209:     my $as_hash = 1;
                   3210:     my %returnhash;
                   3211:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3212:     my %libserv = &all_library();
                   3213:     foreach my $tryserver (keys(%libserv)) {
                   3214:         if ( (  $hostidflag == 1 
                   3215: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3216: 	     || (!defined($hostidflag)) ) {
                   3217: 
1.918     raeburn  3218: 	    if (($domfilter eq '') ||
                   3219: 		(&host_domain($tryserver) eq $domfilter)) {
                   3220:                 my $rep = 
                   3221:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3222:                          $sincefilter.':'.&escape($descfilter).':'.
                   3223:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3224:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3225:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3226:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3227:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3228:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3229:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3230:                          &escape($creationcontext).':'.$domcloner,
                   3231:                          $tryserver);
1.918     raeburn  3232:                 my @pairs=split(/\&/,$rep);
                   3233:                 foreach my $item (@pairs) {
                   3234:                     my ($key,$value)=split(/\=/,$item,2);
                   3235:                     $key = &unescape($key);
                   3236:                     next if ($key =~ /^error: 2 /);
                   3237:                     my $result = &thaw_unescape($value);
                   3238:                     if (ref($result) eq 'HASH') {
                   3239:                         $returnhash{$key}=$result;
                   3240:                     } else {
1.921     raeburn  3241:                         my @responses = split(/:/,$value);
                   3242:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3243:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3244:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3245:                         }
1.1008    raeburn  3246:                     }
1.353     www      3247:                 }
                   3248:             }
                   3249:         }
                   3250:     }
                   3251:     return %returnhash;
                   3252: }
                   3253: 
1.1055    raeburn  3254: sub courselastaccess {
                   3255:     my ($cdom,$cnum,$hostidref) = @_;
                   3256:     my %returnhash;
                   3257:     if ($cdom && $cnum) {
                   3258:         my $chome = &homeserver($cnum,$cdom);
                   3259:         if ($chome ne 'no_host') {
                   3260:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3261:             &extract_lastaccess(\%returnhash,$rep);
                   3262:         }
                   3263:     } else {
                   3264:         if (!$cdom) { $cdom=''; }
                   3265:         my %libserv = &all_library();
                   3266:         foreach my $tryserver (keys(%libserv)) {
                   3267:             if (ref($hostidref) eq 'ARRAY') {
                   3268:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3269:             } 
                   3270:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3271:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3272:                 &extract_lastaccess(\%returnhash,$rep);
                   3273:             }
                   3274:         }
                   3275:     }
                   3276:     return %returnhash;
                   3277: }
                   3278: 
                   3279: sub extract_lastaccess {
                   3280:     my ($returnhash,$rep) = @_;
                   3281:     if (ref($returnhash) eq 'HASH') {
                   3282:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3283:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3284:                  $rep eq '') {
                   3285:             my @pairs=split(/\&/,$rep);
                   3286:             foreach my $item (@pairs) {
                   3287:                 my ($key,$value)=split(/\=/,$item,2);
                   3288:                 $key = &unescape($key);
                   3289:                 next if ($key =~ /^error: 2 /);
                   3290:                 $returnhash->{$key} = &thaw_unescape($value);
                   3291:             }
                   3292:         }
                   3293:     }
                   3294:     return;
                   3295: }
                   3296: 
1.658     raeburn  3297: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3298: 
                   3299: sub dcmailput {
1.685     raeburn  3300:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3301:     my $status = &Apache::lonnet::critical(
1.740     www      3302:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3303:        &escape($message),$server);
1.662     raeburn  3304:     return $status;
                   3305: }
                   3306: 
1.658     raeburn  3307: sub dcmaildump {
                   3308:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3309:     my %returnhash=();
1.846     albertel 3310: 
                   3311:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3312:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3313:                                                          &escape($enddate).':';
                   3314: 	my @esc_senders=map { &escape($_)} @$senders;
                   3315: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3316: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3317:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3318:             if (($key) && ($value)) {
                   3319:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3320:             }
                   3321:         }
                   3322:     }
                   3323:     return %returnhash;
                   3324: }
1.662     raeburn  3325: # ---------------------------------------------------------- Domain roles
                   3326: 
                   3327: sub get_domain_roles {
                   3328:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3329:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3330:         $startdate = '.';
                   3331:     }
1.1018    raeburn  3332:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3333:         $enddate = '.';
                   3334:     }
1.922     raeburn  3335:     my $rolelist;
                   3336:     if (ref($roles) eq 'ARRAY') {
                   3337:         $rolelist = join(':',@{$roles});
                   3338:     }
1.662     raeburn  3339:     my %personnel = ();
1.841     albertel 3340: 
                   3341:     my %servers = &get_servers($dom,'library');
                   3342:     foreach my $tryserver (keys(%servers)) {
                   3343: 	%{$personnel{$tryserver}}=();
                   3344: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3345: 					    &escape($startdate).':'.
                   3346: 					    &escape($enddate).':'.
                   3347: 					    &escape($rolelist), $tryserver))) {
                   3348: 	    my ($key,$value) = split(/\=/,$line,2);
                   3349: 	    if (($key) && ($value)) {
                   3350: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3351: 	    }
                   3352: 	}
1.662     raeburn  3353:     }
                   3354:     return %personnel;
                   3355: }
1.658     raeburn  3356: 
1.149     www      3357: # ----------------------------------------------------------- Check out an item
                   3358: 
1.504     albertel 3359: sub get_first_access {
                   3360:     my ($type,$argsymb)=@_;
1.790     albertel 3361:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3362:     if ($argsymb) { $symb=$argsymb; }
                   3363:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3364:     if ($type eq 'course') {
                   3365: 	$res='course';
                   3366:     } elsif ($type eq 'map') {
1.588     albertel 3367: 	$res=&symbread($map);
                   3368:     } else {
                   3369: 	$res=$symb;
                   3370:     }
                   3371:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3372:     return $times{"$courseid\0$res"};
1.504     albertel 3373: }
                   3374: 
                   3375: sub set_first_access {
                   3376:     my ($type)=@_;
1.790     albertel 3377:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3378:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3379:     if ($type eq 'course') {
                   3380: 	$res='course';
                   3381:     } elsif ($type eq 'map') {
1.588     albertel 3382: 	$res=&symbread($map);
                   3383:     } else {
                   3384: 	$res=$symb;
                   3385:     }
                   3386:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3387:     if (!$firstaccess) {
1.588     albertel 3388: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3389:     }
                   3390:     return 'already_set';
1.504     albertel 3391: }
                   3392: 
1.149     www      3393: sub checkout {
                   3394:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3395:     my $now=time;
                   3396:     my $lonhost=$perlvar{'lonHostID'};
                   3397:     my $infostr=&escape(
1.234     www      3398:                  'CHECKOUTTOKEN&'.
1.149     www      3399:                  $tuname.'&'.
                   3400:                  $tudom.'&'.
                   3401:                  $tcrsid.'&'.
                   3402:                  $symb.'&'.
                   3403: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3404:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3405:     if ($token=~/^error\:/) { 
1.672     albertel 3406:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3407:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3408:                  "</font>");
                   3409:         return ''; 
                   3410:     }
                   3411: 
1.149     www      3412:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3413:     $token=~tr/a-z/A-Z/;
                   3414: 
1.153     www      3415:     my %infohash=('resource.0.outtoken' => $token,
                   3416:                   'resource.0.checkouttime' => $now,
                   3417:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3418: 
                   3419:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3420:        return '';
1.151     www      3421:     } else {
1.672     albertel 3422:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3423:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3424:                  "</font>");
1.149     www      3425:     }    
                   3426: 
                   3427:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3428:                          &escape('Checkout '.$infostr.' - '.
                   3429:                                                  $token)) ne 'ok') {
                   3430: 	return '';
1.151     www      3431:     } else {
1.672     albertel 3432:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3433:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3434:                  "</font>");
1.149     www      3435:     }
1.151     www      3436:     return $token;
1.149     www      3437: }
                   3438: 
                   3439: # ------------------------------------------------------------ Check in an item
                   3440: 
                   3441: sub checkin {
                   3442:     my $token=shift;
1.150     www      3443:     my $now=time;
                   3444:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3445:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3446:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3447:     $dtoken=~s/\W/\_/g;
1.234     www      3448:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3449:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3450: 
1.154     www      3451:     unless (($tuname) && ($tudom)) {
                   3452:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3453:         return '';
                   3454:     }
                   3455:     
                   3456:     unless (&allowed('mgr',$tcrsid)) {
                   3457:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3458:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3459:         return '';
                   3460:     }
                   3461: 
1.153     www      3462:     my %infohash=('resource.0.intoken' => $token,
                   3463:                   'resource.0.checkintime' => $now,
                   3464:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3465: 
                   3466:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3467:        return '';
                   3468:     }    
                   3469: 
                   3470:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3471:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3472: 	return '';
                   3473:     }
                   3474: 
                   3475:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3476: }
                   3477: 
                   3478: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3479: 
                   3480: sub expirespread {
                   3481:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3482:     my $cid=$env{'request.course.id'}; 
1.110     www      3483:     if ($cid) {
                   3484:        my $now=time;
                   3485:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3486:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3487:                             $env{'course.'.$cid.'.num'}.
1.110     www      3488: 	        	    ':nohist_expirationdates:'.
                   3489:                             &escape($key).'='.$now,
1.620     albertel 3490:                             $env{'course.'.$cid.'.home'})
1.110     www      3491:     }
                   3492:     return 'ok';
1.14      www      3493: }
                   3494: 
1.109     www      3495: # ----------------------------------------------------- Devalidate Spreadsheets
                   3496: 
                   3497: sub devalidate {
1.325     www      3498:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3499:     my $cid=$env{'request.course.id'}; 
1.109     www      3500:     if ($cid) {
1.391     matthew  3501:         # delete the stored spreadsheets for
                   3502:         # - the student level sheet of this user in course's homespace
                   3503:         # - the assessment level sheet for this resource 
                   3504:         #   for this user in user's homespace
1.553     albertel 3505: 	# - current conditional state info
1.325     www      3506: 	my $key=$uname.':'.$udom.':';
1.109     www      3507:         my $status=
1.299     matthew  3508: 	    &del('nohist_calculatedsheets',
1.391     matthew  3509: 		 [$key.'studentcalc:'],
1.620     albertel 3510: 		 $env{'course.'.$cid.'.domain'},
                   3511: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3512: 		.' '.
                   3513: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3514: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3515:         unless ($status eq 'ok ok') {
                   3516:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3517:                     $uname.' at '.$udom.' for '.
1.109     www      3518: 		    $symb.': '.$status);
1.133     albertel 3519:         }
1.553     albertel 3520: 	&delenv('user.state.'.$cid);
1.109     www      3521:     }
                   3522: }
                   3523: 
1.265     albertel 3524: sub get_scalar {
                   3525:     my ($string,$end) = @_;
                   3526:     my $value;
                   3527:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3528: 	$value = $1;
                   3529:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3530: 	$value = $1;
                   3531:     }
                   3532:     return &unescape($value);
                   3533: }
                   3534: 
                   3535: sub array2str {
                   3536:   my (@array) = @_;
                   3537:   my $result=&arrayref2str(\@array);
                   3538:   $result=~s/^__ARRAY_REF__//;
                   3539:   $result=~s/__END_ARRAY_REF__$//;
                   3540:   return $result;
                   3541: }
                   3542: 
1.204     albertel 3543: sub arrayref2str {
                   3544:   my ($arrayref) = @_;
1.265     albertel 3545:   my $result='__ARRAY_REF__';
1.204     albertel 3546:   foreach my $elem (@$arrayref) {
1.265     albertel 3547:     if(ref($elem) eq 'ARRAY') {
                   3548:       $result.=&arrayref2str($elem).'&';
                   3549:     } elsif(ref($elem) eq 'HASH') {
                   3550:       $result.=&hashref2str($elem).'&';
                   3551:     } elsif(ref($elem)) {
                   3552:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3553:     } else {
                   3554:       $result.=&escape($elem).'&';
                   3555:     }
                   3556:   }
                   3557:   $result=~s/\&$//;
1.265     albertel 3558:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3559:   return $result;
                   3560: }
                   3561: 
1.168     albertel 3562: sub hash2str {
1.204     albertel 3563:   my (%hash) = @_;
                   3564:   my $result=&hashref2str(\%hash);
1.265     albertel 3565:   $result=~s/^__HASH_REF__//;
                   3566:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3567:   return $result;
                   3568: }
                   3569: 
                   3570: sub hashref2str {
                   3571:   my ($hashref)=@_;
1.265     albertel 3572:   my $result='__HASH_REF__';
1.800     albertel 3573:   foreach my $key (sort(keys(%$hashref))) {
                   3574:     if (ref($key) eq 'ARRAY') {
                   3575:       $result.=&arrayref2str($key).'=';
                   3576:     } elsif (ref($key) eq 'HASH') {
                   3577:       $result.=&hashref2str($key).'=';
                   3578:     } elsif (ref($key)) {
1.265     albertel 3579:       $result.='=';
1.800     albertel 3580:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3581:     } else {
1.800     albertel 3582: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3583:     }
                   3584: 
1.800     albertel 3585:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3586:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3587:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3588:       $result.=&hashref2str($hashref->{$key}).'&';
                   3589:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3590:        $result.='&';
1.800     albertel 3591:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3592:     } else {
1.800     albertel 3593:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3594:     }
                   3595:   }
1.168     albertel 3596:   $result=~s/\&$//;
1.265     albertel 3597:   $result .= '__END_HASH_REF__';
1.168     albertel 3598:   return $result;
                   3599: }
                   3600: 
                   3601: sub str2hash {
1.265     albertel 3602:     my ($string)=@_;
                   3603:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3604:     return %$hash;
                   3605: }
                   3606: 
                   3607: sub str2hashref {
1.168     albertel 3608:   my ($string) = @_;
1.265     albertel 3609: 
                   3610:   my %hash;
                   3611: 
                   3612:   if($string !~ /^__HASH_REF__/) {
                   3613:       if (! ($string eq '' || !defined($string))) {
                   3614: 	  $hash{'error'}='Not hash reference';
                   3615:       }
                   3616:       return (\%hash, $string);
                   3617:   }
                   3618: 
                   3619:   $string =~ s/^__HASH_REF__//;
                   3620: 
                   3621:   while($string !~ /^__END_HASH_REF__/) {
                   3622:       #key
                   3623:       my $key='';
                   3624:       if($string =~ /^__HASH_REF__/) {
                   3625:           ($key, $string)=&str2hashref($string);
                   3626:           if(defined($key->{'error'})) {
                   3627:               $hash{'error'}='Bad data';
                   3628:               return (\%hash, $string);
                   3629:           }
                   3630:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3631:           ($key, $string)=&str2arrayref($string);
                   3632:           if($key->[0] eq 'Array reference error') {
                   3633:               $hash{'error'}='Bad data';
                   3634:               return (\%hash, $string);
                   3635:           }
                   3636:       } else {
                   3637:           $string =~ s/^(.*?)=//;
1.267     albertel 3638: 	  $key=&unescape($1);
1.265     albertel 3639:       }
                   3640:       $string =~ s/^=//;
                   3641: 
                   3642:       #value
                   3643:       my $value='';
                   3644:       if($string =~ /^__HASH_REF__/) {
                   3645:           ($value, $string)=&str2hashref($string);
                   3646:           if(defined($value->{'error'})) {
                   3647:               $hash{'error'}='Bad data';
                   3648:               return (\%hash, $string);
                   3649:           }
                   3650:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3651:           ($value, $string)=&str2arrayref($string);
                   3652:           if($value->[0] eq 'Array reference error') {
                   3653:               $hash{'error'}='Bad data';
                   3654:               return (\%hash, $string);
                   3655:           }
                   3656:       } else {
                   3657: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3658:       }
                   3659:       $string =~ s/^&//;
                   3660: 
                   3661:       $hash{$key}=$value;
1.204     albertel 3662:   }
1.265     albertel 3663: 
                   3664:   $string =~ s/^__END_HASH_REF__//;
                   3665: 
                   3666:   return (\%hash, $string);
1.204     albertel 3667: }
                   3668: 
                   3669: sub str2array {
1.265     albertel 3670:     my ($string)=@_;
                   3671:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3672:     return @$array;
                   3673: }
                   3674: 
                   3675: sub str2arrayref {
1.204     albertel 3676:   my ($string) = @_;
1.265     albertel 3677:   my @array;
                   3678: 
                   3679:   if($string !~ /^__ARRAY_REF__/) {
                   3680:       if (! ($string eq '' || !defined($string))) {
                   3681: 	  $array[0]='Array reference error';
                   3682:       }
                   3683:       return (\@array, $string);
                   3684:   }
                   3685: 
                   3686:   $string =~ s/^__ARRAY_REF__//;
                   3687: 
                   3688:   while($string !~ /^__END_ARRAY_REF__/) {
                   3689:       my $value='';
                   3690:       if($string =~ /^__HASH_REF__/) {
                   3691:           ($value, $string)=&str2hashref($string);
                   3692:           if(defined($value->{'error'})) {
                   3693:               $array[0] ='Array reference error';
                   3694:               return (\@array, $string);
                   3695:           }
                   3696:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3697:           ($value, $string)=&str2arrayref($string);
                   3698:           if($value->[0] eq 'Array reference error') {
                   3699:               $array[0] ='Array reference error';
                   3700:               return (\@array, $string);
                   3701:           }
                   3702:       } else {
                   3703: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3704:       }
                   3705:       $string =~ s/^&//;
                   3706: 
                   3707:       push(@array, $value);
1.191     harris41 3708:   }
1.265     albertel 3709: 
                   3710:   $string =~ s/^__END_ARRAY_REF__//;
                   3711: 
                   3712:   return (\@array, $string);
1.168     albertel 3713: }
                   3714: 
1.167     albertel 3715: # -------------------------------------------------------------------Temp Store
                   3716: 
1.168     albertel 3717: sub tmpreset {
                   3718:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3719:   if (!$symb) {
                   3720:     $symb=&symbread();
1.620     albertel 3721:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3722:   }
                   3723:   $symb=escape($symb);
                   3724: 
1.620     albertel 3725:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3726:   $namespace=~s/\//\_/g;
                   3727:   $namespace=~s/\W//g;
                   3728: 
1.620     albertel 3729:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3730:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3731:   if ($domain eq 'public' && $stuname eq 'public') {
                   3732:       $stuname=$ENV{'REMOTE_ADDR'};
                   3733:   }
1.168     albertel 3734:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3735:   my %hash;
                   3736:   if (tie(%hash,'GDBM_File',
                   3737: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3738: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3739:     foreach my $key (keys(%hash)) {
1.180     albertel 3740:       if ($key=~ /:$symb/) {
1.168     albertel 3741: 	delete($hash{$key});
                   3742:       }
                   3743:     }
                   3744:   }
                   3745: }
                   3746: 
1.167     albertel 3747: sub tmpstore {
1.168     albertel 3748:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3749: 
                   3750:   if (!$symb) {
                   3751:     $symb=&symbread();
1.620     albertel 3752:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3753:   }
                   3754:   $symb=escape($symb);
                   3755: 
                   3756:   if (!$namespace) {
                   3757:     # I don't think we would ever want to store this for a course.
                   3758:     # it seems this will only be used if we don't have a course.
1.620     albertel 3759:     #$namespace=$env{'request.course.id'};
1.168     albertel 3760:     #if (!$namespace) {
1.620     albertel 3761:       $namespace=$env{'request.state'};
1.168     albertel 3762:     #}
                   3763:   }
                   3764:   $namespace=~s/\//\_/g;
                   3765:   $namespace=~s/\W//g;
1.620     albertel 3766:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3767:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3768:   if ($domain eq 'public' && $stuname eq 'public') {
                   3769:       $stuname=$ENV{'REMOTE_ADDR'};
                   3770:   }
1.168     albertel 3771:   my $now=time;
                   3772:   my %hash;
                   3773:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3774:   if (tie(%hash,'GDBM_File',
                   3775: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3776: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3777:     $hash{"version:$symb"}++;
                   3778:     my $version=$hash{"version:$symb"};
                   3779:     my $allkeys=''; 
                   3780:     foreach my $key (keys(%$storehash)) {
                   3781:       $allkeys.=$key.':';
1.591     albertel 3782:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3783:     }
                   3784:     $hash{"$version:$symb:timestamp"}=$now;
                   3785:     $allkeys.='timestamp';
                   3786:     $hash{"$version:keys:$symb"}=$allkeys;
                   3787:     if (untie(%hash)) {
                   3788:       return 'ok';
                   3789:     } else {
                   3790:       return "error:$!";
                   3791:     }
                   3792:   } else {
                   3793:     return "error:$!";
                   3794:   }
                   3795: }
1.167     albertel 3796: 
1.168     albertel 3797: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3798: 
1.168     albertel 3799: sub tmprestore {
                   3800:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3801: 
1.168     albertel 3802:   if (!$symb) {
                   3803:     $symb=&symbread();
1.620     albertel 3804:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3805:   }
                   3806:   $symb=escape($symb);
                   3807: 
1.620     albertel 3808:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3809: 
1.620     albertel 3810:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3811:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3812:   if ($domain eq 'public' && $stuname eq 'public') {
                   3813:       $stuname=$ENV{'REMOTE_ADDR'};
                   3814:   }
1.168     albertel 3815:   my %returnhash;
                   3816:   $namespace=~s/\//\_/g;
                   3817:   $namespace=~s/\W//g;
                   3818:   my %hash;
                   3819:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3820:   if (tie(%hash,'GDBM_File',
                   3821: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3822: 	  &GDBM_READER(),0640)) {
1.168     albertel 3823:     my $version=$hash{"version:$symb"};
                   3824:     $returnhash{'version'}=$version;
                   3825:     my $scope;
                   3826:     for ($scope=1;$scope<=$version;$scope++) {
                   3827:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3828:       my @keys=split(/:/,$vkeys);
                   3829:       my $key;
                   3830:       $returnhash{"$scope:keys"}=$vkeys;
                   3831:       foreach $key (@keys) {
1.591     albertel 3832: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3833: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3834:       }
                   3835:     }
1.168     albertel 3836:     if (!(untie(%hash))) {
                   3837:       return "error:$!";
                   3838:     }
                   3839:   } else {
                   3840:     return "error:$!";
                   3841:   }
                   3842:   return %returnhash;
1.167     albertel 3843: }
                   3844: 
1.9       www      3845: # ----------------------------------------------------------------------- Store
                   3846: 
                   3847: sub store {
1.124     www      3848:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3849:     my $home='';
                   3850: 
1.168     albertel 3851:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3852: 
1.213     www      3853:     $symb=&symbclean($symb);
1.122     albertel 3854:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3855: 
1.620     albertel 3856:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3857:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3858: 
                   3859:     &devalidate($symb,$stuname,$domain);
1.109     www      3860: 
                   3861:     $symb=escape($symb);
1.187     www      3862:     if (!$namespace) { 
1.620     albertel 3863:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3864:           return ''; 
                   3865:        } 
                   3866:     }
1.620     albertel 3867:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3868: 
                   3869:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3870:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3871: 
1.12      www      3872:     my $namevalue='';
1.800     albertel 3873:     foreach my $key (keys(%$storehash)) {
                   3874:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3875:     }
1.12      www      3876:     $namevalue=~s/\&$//;
1.187     www      3877:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3878:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3879: }
                   3880: 
1.47      www      3881: # -------------------------------------------------------------- Critical Store
                   3882: 
                   3883: sub cstore {
1.124     www      3884:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3885:     my $home='';
                   3886: 
1.168     albertel 3887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3888: 
1.213     www      3889:     $symb=&symbclean($symb);
1.122     albertel 3890:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3891: 
1.620     albertel 3892:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3893:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3894: 
                   3895:     &devalidate($symb,$stuname,$domain);
1.109     www      3896: 
                   3897:     $symb=escape($symb);
1.187     www      3898:     if (!$namespace) { 
1.620     albertel 3899:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3900:           return ''; 
                   3901:        } 
                   3902:     }
1.620     albertel 3903:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3904: 
                   3905:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3906:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3907: 
1.47      www      3908:     my $namevalue='';
1.800     albertel 3909:     foreach my $key (keys(%$storehash)) {
                   3910:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3911:     }
1.47      www      3912:     $namevalue=~s/\&$//;
1.187     www      3913:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3914:     return critical
                   3915:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3916: }
                   3917: 
1.9       www      3918: # --------------------------------------------------------------------- Restore
                   3919: 
                   3920: sub restore {
1.124     www      3921:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3922:     my $home='';
                   3923: 
1.168     albertel 3924:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3925: 
1.122     albertel 3926:     if (!$symb) {
                   3927:       unless ($symb=escape(&symbread())) { return ''; }
                   3928:     } else {
1.213     www      3929:       $symb=&escape(&symbclean($symb));
1.122     albertel 3930:     }
1.188     www      3931:     if (!$namespace) { 
1.620     albertel 3932:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3933:           return ''; 
                   3934:        } 
                   3935:     }
1.620     albertel 3936:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3937:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3938:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3939:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3940: 
1.12      www      3941:     my %returnhash=();
1.800     albertel 3942:     foreach my $line (split(/\&/,$answer)) {
                   3943: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3944:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3945:     }
1.75      www      3946:     my $version;
                   3947:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3948:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3949:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3950:        }
1.75      www      3951:     }
1.13      www      3952:     return %returnhash;
1.34      www      3953: }
                   3954: 
                   3955: # ---------------------------------------------------------- Course Description
                   3956: 
                   3957: sub coursedescription {
1.731     albertel 3958:     my ($courseid,$args)=@_;
1.34      www      3959:     $courseid=~s/^\///;
1.49      www      3960:     $courseid=~s/\_/\//g;
1.34      www      3961:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3962:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3963:     my $normalid=$cdomain.'_'.$cnum;
                   3964:     # need to always cache even if we get errors otherwise we keep 
                   3965:     # trying and trying and trying to get the course description.
                   3966:     my %envhash=();
                   3967:     my %returnhash=();
1.731     albertel 3968:     
                   3969:     my $expiretime=600;
                   3970:     if ($env{'request.course.id'} eq $normalid) {
                   3971: 	$expiretime=120;
                   3972:     }
                   3973: 
                   3974:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3975:     if (!$args->{'freshen_cache'}
                   3976: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3977: 	foreach my $key (keys(%env)) {
                   3978: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3979: 	    my ($setting) = $1;
                   3980: 	    $returnhash{$setting} = $env{$key};
                   3981: 	}
                   3982: 	return %returnhash;
                   3983:     }
                   3984: 
                   3985:     # get the data agin
                   3986:     if (!$args->{'one_time'}) {
                   3987: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3988:     }
1.811     albertel 3989: 
1.34      www      3990:     if ($chome ne 'no_host') {
1.302     albertel 3991:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3992:        if (!exists($returnhash{'con_lost'})) {
                   3993:            $returnhash{'home'}= $chome;
                   3994: 	   $returnhash{'domain'} = $cdomain;
                   3995: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3996:            if (!defined($returnhash{'type'})) {
                   3997:                $returnhash{'type'} = 'Course';
                   3998:            }
1.130     albertel 3999:            while (my ($name,$value) = each %returnhash) {
1.53      www      4000:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4001:            }
1.270     www      4002:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4003:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4004: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4005:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4006:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4007:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4008:        }
                   4009:     }
1.731     albertel 4010:     if (!$args->{'one_time'}) {
1.949     raeburn  4011: 	&appenv(\%envhash);
1.731     albertel 4012:     }
1.302     albertel 4013:     return %returnhash;
1.461     www      4014: }
                   4015: 
1.1056.4.5  raeburn  4016: sub update_released_required {
                   4017:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4018:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4019:         $cid = $env{'request.course.id'};
                   4020:         $cdom = $env{'course.'.$cid.'.domain'};
                   4021:         $cnum = $env{'course.'.$cid.'.num'};
                   4022:         $chome = $env{'course.'.$cid.'.home'};
                   4023:     }
                   4024:     if ($needsrelease) {
                   4025:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4026:         my $needsupdate;
                   4027:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4028:             $needsupdate = 1;
                   4029:         } else {
                   4030:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4031:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4032:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4033:                 $needsupdate = 1;
                   4034:             }
                   4035:         }
                   4036:         if ($needsupdate) {
                   4037:             my %needshash = (
                   4038:                              'internal.releaserequired' => $needsrelease,
                   4039:                             );
                   4040:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4041:             if ($putresult eq 'ok') {
                   4042:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4043:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4044:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4045:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4046:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4047:                 }
                   4048:             }
                   4049:         }
                   4050:     }
                   4051:     return;
                   4052: }
                   4053: 
1.461     www      4054: # -------------------------------------------------See if a user is privileged
                   4055: 
                   4056: sub privileged {
                   4057:     my ($username,$domain)=@_;
                   4058:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4059: 			&homeserver($username,$domain));
1.1033    raeburn  4060:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4061:         ($rolesdump =~ /^error:/)) {
                   4062:         return 0;
                   4063:     }
1.461     www      4064:     my $now=time;
                   4065:     if ($rolesdump ne '') {
1.800     albertel 4066:         foreach my $entry (split(/&/,$rolesdump)) {
                   4067: 	    if ($entry!~/^rolesdef_/) {
                   4068: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4069: 		$area=~s/\_\w\w$//;
                   4070: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4071: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4072: 		    my $active=1;
                   4073: 		    if ($tend) {
                   4074: 			if ($tend<$now) { $active=0; }
                   4075: 		    }
                   4076: 		    if ($tstart) {
                   4077: 			if ($tstart>$now) { $active=0; }
                   4078: 		    }
                   4079: 		    if ($active) { return 1; }
                   4080: 		}
                   4081: 	    }
                   4082: 	}
                   4083:     }
                   4084:     return 0;
1.9       www      4085: }
1.1       albertel 4086: 
1.103     harris41 4087: # -------------------------------------------------------- Get user privileges
1.11      www      4088: 
                   4089: sub rolesinit {
                   4090:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4091:     my $now=time;
                   4092:     my %userroles = ('user.login.time' => $now);
1.1056.4.3  raeburn  4093:     my $extra = &freeze_escape({'clientcheckrole' => 1});
                   4094:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4095:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4096:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4097:         return \%userroles;
                   4098:     }
1.11      www      4099:     my %allroles=();
1.678     raeburn  4100:     my %allgroups=();   
                   4101:     my $group_privs;
1.11      www      4102: 
                   4103:     if ($rolesdump ne '') {
1.800     albertel 4104:         foreach my $entry (split(/&/,$rolesdump)) {
                   4105: 	  if ($entry!~/^rolesdef_/) {
                   4106:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4107: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4108:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4109: 	    if ($role=~/^cr/) { 
1.807     albertel 4110: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4111: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4112: 		    ($tend,$tstart)=split('_',$trest);
                   4113: 		} else {
                   4114: 		    $trole=$role;
                   4115: 		}
1.678     raeburn  4116:             } elsif ($role =~ m|^gr/|) {
                   4117:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4118:                 ($trole,$group_privs) = split(/\//,$trole);
                   4119:                 $group_privs = &unescape($group_privs);
1.587     albertel 4120: 	    } else {
                   4121: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4122: 	    }
1.743     albertel 4123: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4124: 					 $username);
                   4125: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4126:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4127:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4128:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4129: 		my $spec=$trole.'.'.$area;
                   4130: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4131: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4132:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4133:                 } elsif ($trole eq 'gr') {
                   4134:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4135: 		} else {
1.567     raeburn  4136:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4137: 		}
1.12      www      4138:             }
1.662     raeburn  4139:           }
1.191     harris41 4140:         }
1.743     albertel 4141:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4142:         $userroles{'user.adv'}    = $adv;
                   4143: 	$userroles{'user.author'} = $author;
1.620     albertel 4144:         $env{'user.adv'}=$adv;
1.11      www      4145:     }
1.743     albertel 4146:     return \%userroles;  
1.11      www      4147: }
                   4148: 
1.567     raeburn  4149: sub set_arearole {
                   4150:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4151: # log the associated role with the area
                   4152:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4153:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4154: }
                   4155: 
                   4156: sub custom_roleprivs {
                   4157:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4158:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4159:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4160:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4161:         my ($rdummy,$roledef)=
                   4162:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4163:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4164:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4165:             if (defined($syspriv)) {
1.1043    raeburn  4166:                 if ($trest =~ /^$match_community$/) {
                   4167:                     $syspriv =~ s/bre\&S//; 
                   4168:                 }
1.567     raeburn  4169:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4170:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4171:             }
                   4172:             if ($tdomain ne '') {
                   4173:                 if (defined($dompriv)) {
                   4174:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4175:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4176:                 }
                   4177:                 if (($trest ne '') && (defined($coursepriv))) {
                   4178:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4179:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4180:                 }
                   4181:             }
                   4182:         }
                   4183:     }
                   4184: }
                   4185: 
1.678     raeburn  4186: sub group_roleprivs {
                   4187:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4188:     my $access = 1;
                   4189:     my $now = time;
                   4190:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4191:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4192:     if ($access) {
1.811     albertel 4193:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4194:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4195:     }
                   4196: }
1.567     raeburn  4197: 
                   4198: sub standard_roleprivs {
                   4199:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4200:     if (defined($pr{$trole.':s'})) {
                   4201:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4202:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4203:     }
                   4204:     if ($tdomain ne '') {
                   4205:         if (defined($pr{$trole.':d'})) {
                   4206:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4207:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4208:         }
                   4209:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4210:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4211:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4212:         }
                   4213:     }
                   4214: }
                   4215: 
                   4216: sub set_userprivs {
1.1056.4.2  raeburn  4217:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4218:     my $author=0;
                   4219:     my $adv=0;
1.678     raeburn  4220:     my %grouproles = ();
                   4221:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4222:         my @groupkeys;
1.1000    raeburn  4223:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4224:             push(@groupkeys,$role);
                   4225:         }
                   4226:         if (ref($groups_roles) eq 'HASH') {
                   4227:             foreach my $key (keys(%{$groups_roles})) {
                   4228:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4229:                     push(@groupkeys,$key);
                   4230:                 }
                   4231:             }
                   4232:         }
                   4233:         if (@groupkeys > 0) {
                   4234:             foreach my $role (@groupkeys) {
                   4235:                 my ($trole,$area,$sec,$extendedarea);
                   4236:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4237:                     $trole = $1;
                   4238:                     $area = $2;
                   4239:                     $sec = $3;
                   4240:                     $extendedarea = $area.$sec;
                   4241:                     if (exists($$allgroups{$area})) {
                   4242:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4243:                             my $spec = $trole.'.'.$extendedarea;
                   4244:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4245:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4246:                         }
1.678     raeburn  4247:                     }
                   4248:                 }
                   4249:             }
                   4250:         }
                   4251:     }
1.800     albertel 4252:     foreach my $group (keys(%grouproles)) {
                   4253:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4254:     }
1.800     albertel 4255:     foreach my $role (keys(%{$allroles})) {
                   4256:         my %thesepriv;
1.941     raeburn  4257:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4258:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4259:             if ($item ne '') {
                   4260:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4261:                 if ($restrictions eq '') {
                   4262:                     $thesepriv{$privilege}='F';
                   4263:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4264:                     $thesepriv{$privilege}.=$restrictions;
                   4265:                 }
                   4266:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4267:             }
                   4268:         }
                   4269:         my $thesestr='';
1.800     albertel 4270:         foreach my $priv (keys(%thesepriv)) {
                   4271: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4272: 	}
                   4273:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4274:     }
                   4275:     return ($author,$adv);
                   4276: }
                   4277: 
1.994     raeburn  4278: sub role_status {
1.1002    raeburn  4279:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4280:     my @pwhere = ();
                   4281:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4282:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4283:         unless (!defined($$role) || $$role eq '') {
                   4284:             $$where=join('.',@pwhere);
                   4285:             $$trolecode=$$role.'.'.$$where;
                   4286:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4287:             $$tstatus='is';
                   4288:             if ($$tstart && $$tstart>$then) {
                   4289:                 $$tstatus='future';
1.1034    raeburn  4290:                 if ($$tstart<$now) {
                   4291:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4292:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4293:                             my (%allroles,%allgroups,$group_privs,
                   4294:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4295:                             my %userroles = (
                   4296:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4297:                             );
1.1056.4.2  raeburn  4298:                             @rolecodes = ('cm');
1.1002    raeburn  4299:                             my $spec=$$role.'.'.$$where;
                   4300:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4301:                             if ($$role =~ /^cr\//) {
                   4302:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4303:                                 push(@rolecodes,'cr');
1.1002    raeburn  4304:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4305:                                 push(@rolecodes,$$role);
1.1002    raeburn  4306:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4307:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4308:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4309:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4310:                                 $group_privs = &unescape($group_privs);
                   4311:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4312:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4313:                                 if (keys(%course_roles) > 0) {
                   4314:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4315:                                     if ($tdomain ne '' && $tnum ne '') {
                   4316:                                         foreach my $key (keys(%course_roles)) {
                   4317:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4318:                                                 my $crsrole = $1;
                   4319:                                                 my $crssec = $2;
                   4320:                                                 if ($crsrole =~ /^cr/) {
                   4321:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4322:                                                         push(@rolecodes,'cr');
                   4323:                                                     }
                   4324:                                                 } else {
                   4325:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4326:                                                         push(@rolecodes,$crsrole);
                   4327:                                                     }
                   4328:                                                 }
                   4329:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4330:                                                 if ($crssec ne '') {
                   4331:                                                     $rolekey .= '/'.$crssec;
                   4332:                                                 }
                   4333:                                                 $rolekey .= './';
                   4334:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4335:                                             }
                   4336:                                         }
                   4337:                                     }
                   4338:                                 }
1.1002    raeburn  4339:                             } else {
1.1056.4.2  raeburn  4340:                                 push(@rolecodes,$$role);
1.1002    raeburn  4341:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4342:                             }
1.1056.4.2  raeburn  4343:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4344:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4345:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4346:                         }
                   4347:                     }
1.1034    raeburn  4348:                     $$tstatus = 'is';
1.1002    raeburn  4349:                 }
1.994     raeburn  4350:             }
                   4351:             if ($$tend) {
                   4352:                 if ($$tend<$then) {
                   4353:                     $$tstatus='expired';
                   4354:                 } elsif ($$tend<$now) {
                   4355:                     $$tstatus='will_not';
                   4356:                 }
                   4357:             }
                   4358:         }
                   4359:     }
                   4360: }
                   4361: 
                   4362: sub check_adhoc_privs {
1.1002    raeburn  4363:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4364:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4365:     if ($env{$cckey}) {
                   4366:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4367:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4368:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4369:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4370:         }
                   4371:     } else {
                   4372:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4373:     }
                   4374: }
                   4375: 
                   4376: sub set_adhoc_privileges {
                   4377: # role can be cc or ca
                   4378:     my ($dcdom,$pickedcourse,$role) = @_;
                   4379:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4380:     my $spec = $role.'.'.$area;
                   4381:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4382:                                   $env{'user.name'});
                   4383:     my %ccrole = ();
                   4384:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4385:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4386:     &appenv(\%userroles,[$role,'cm']);
                   4387:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4388:     &appenv( {'request.role'        => $spec,
                   4389:               'request.role.domain' => $dcdom,
                   4390:               'request.course.sec'  => ''
                   4391:              }
                   4392:            );
                   4393:     my $tadv=0;
                   4394:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4395:     &appenv({'request.role.adv'    => $tadv});
                   4396: }
                   4397: 
1.12      www      4398: # --------------------------------------------------------------- get interface
                   4399: 
                   4400: sub get {
1.131     albertel 4401:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4402:    my $items='';
1.800     albertel 4403:    foreach my $item (@$storearr) {
                   4404:        $items.=&escape($item).'&';
1.191     harris41 4405:    }
1.12      www      4406:    $items=~s/\&$//;
1.620     albertel 4407:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4408:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4409:    my $uhome=&homeserver($uname,$udomain);
                   4410: 
1.133     albertel 4411:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4412:    my @pairs=split(/\&/,$rep);
1.273     albertel 4413:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4414:      return @pairs;
                   4415:    }
1.15      www      4416:    my %returnhash=();
1.42      www      4417:    my $i=0;
1.800     albertel 4418:    foreach my $item (@$storearr) {
                   4419:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4420:       $i++;
1.191     harris41 4421:    }
1.15      www      4422:    return %returnhash;
1.27      www      4423: }
                   4424: 
                   4425: # --------------------------------------------------------------- del interface
                   4426: 
                   4427: sub del {
1.133     albertel 4428:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4429:    my $items='';
1.800     albertel 4430:    foreach my $item (@$storearr) {
                   4431:        $items.=&escape($item).'&';
1.191     harris41 4432:    }
1.984     neumanie 4433: 
1.27      www      4434:    $items=~s/\&$//;
1.620     albertel 4435:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4436:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4437:    my $uhome=&homeserver($uname,$udomain);
                   4438:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4439: }
                   4440: 
                   4441: # -------------------------------------------------------------- dump interface
                   4442: 
                   4443: sub dump {
1.755     albertel 4444:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4445:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4446:     if (!$uname) { $uname=$env{'user.name'}; }
                   4447:     my $uhome=&homeserver($uname,$udomain);
                   4448:     if ($regexp) {
                   4449: 	$regexp=&escape($regexp);
                   4450:     } else {
                   4451: 	$regexp='.';
                   4452:     }
                   4453:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4454:     my @pairs=split(/\&/,$rep);
                   4455:     my %returnhash=();
                   4456:     foreach my $item (@pairs) {
                   4457: 	my ($key,$value)=split(/=/,$item,2);
                   4458: 	$key = &unescape($key);
                   4459: 	next if ($key =~ /^error: 2 /);
                   4460: 	$returnhash{$key}=&thaw_unescape($value);
                   4461:     }
                   4462:     return %returnhash;
1.407     www      4463: }
                   4464: 
1.717     albertel 4465: # --------------------------------------------------------- dumpstore interface
                   4466: 
                   4467: sub dumpstore {
                   4468:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4469:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4470:    if (!$uname) { $uname=$env{'user.name'}; }
                   4471:    my $uhome=&homeserver($uname,$udomain);
                   4472:    if ($regexp) {
                   4473:        $regexp=&escape($regexp);
                   4474:    } else {
                   4475:        $regexp='.';
                   4476:    }
                   4477:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4478:    my @pairs=split(/\&/,$rep);
                   4479:    my %returnhash=();
                   4480:    foreach my $item (@pairs) {
                   4481:        my ($key,$value)=split(/=/,$item,2);
                   4482:        next if ($key =~ /^error: 2 /);
                   4483:        $returnhash{$key}=&thaw_unescape($value);
                   4484:    }
                   4485:    return %returnhash;
1.717     albertel 4486: }
                   4487: 
1.407     www      4488: # -------------------------------------------------------------- keys interface
                   4489: 
                   4490: sub getkeys {
                   4491:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4492:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4493:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4494:    my $uhome=&homeserver($uname,$udomain);
                   4495:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4496:    my @keyarray=();
1.800     albertel 4497:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4498:       next if ($key =~ /^error: 2 /);
1.800     albertel 4499:       push(@keyarray,&unescape($key));
1.407     www      4500:    }
                   4501:    return @keyarray;
1.318     matthew  4502: }
                   4503: 
1.319     matthew  4504: # --------------------------------------------------------------- currentdump
                   4505: sub currentdump {
1.328     matthew  4506:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4507:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4508:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4509:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4510:    my $uhome = &homeserver($sname,$sdom);
                   4511:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4512:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4513:    #
1.318     matthew  4514:    my %returnhash=();
1.319     matthew  4515:    #
                   4516:    if ($rep eq "unknown_cmd") { 
                   4517:        # an old lond will not know currentdump
                   4518:        # Do a dump and make it look like a currentdump
1.822     albertel 4519:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4520:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4521:        my %hash = @tmp;
                   4522:        @tmp=();
1.424     matthew  4523:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4524:    } else {
                   4525:        my @pairs=split(/\&/,$rep);
1.800     albertel 4526:        foreach my $pair (@pairs) {
                   4527:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4528:            my ($symb,$param) = split(/:/,$key);
                   4529:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4530:                                                         &thaw_unescape($value);
1.319     matthew  4531:        }
1.191     harris41 4532:    }
1.12      www      4533:    return %returnhash;
1.424     matthew  4534: }
                   4535: 
                   4536: sub convert_dump_to_currentdump{
                   4537:     my %hash = %{shift()};
                   4538:     my %returnhash;
                   4539:     # Code ripped from lond, essentially.  The only difference
                   4540:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4541:     # we might run in to problems with parameter names =~ /^v\./
                   4542:     while (my ($key,$value) = each(%hash)) {
                   4543:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4544: 	$symb  = &unescape($symb);
                   4545: 	$param = &unescape($param);
1.424     matthew  4546:         next if ($v eq 'version' || $symb eq 'keys');
                   4547:         next if (exists($returnhash{$symb}) &&
                   4548:                  exists($returnhash{$symb}->{$param}) &&
                   4549:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4550:         $returnhash{$symb}->{$param}=$value;
                   4551:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4552:     }
                   4553:     #
                   4554:     # Remove all of the keys in the hashes which keep track of
                   4555:     # the version of the parameter.
                   4556:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4557:         # use a foreach because we are going to delete from the hash.
                   4558:         foreach my $key (keys(%$param_hash)) {
                   4559:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4560:         }
                   4561:     }
                   4562:     return \%returnhash;
1.12      www      4563: }
                   4564: 
1.627     albertel 4565: # ------------------------------------------------------ critical inc interface
                   4566: 
                   4567: sub cinc {
                   4568:     return &inc(@_,'critical');
                   4569: }
                   4570: 
1.449     matthew  4571: # --------------------------------------------------------------- inc interface
                   4572: 
                   4573: sub inc {
1.627     albertel 4574:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4575:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4576:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4577:     my $uhome=&homeserver($uname,$udomain);
                   4578:     my $items='';
                   4579:     if (! ref($store)) {
                   4580:         # got a single value, so use that instead
                   4581:         $items = &escape($store).'=&';
                   4582:     } elsif (ref($store) eq 'SCALAR') {
                   4583:         $items = &escape($$store).'=&';        
                   4584:     } elsif (ref($store) eq 'ARRAY') {
                   4585:         $items = join('=&',map {&escape($_);} @{$store});
                   4586:     } elsif (ref($store) eq 'HASH') {
                   4587:         while (my($key,$value) = each(%{$store})) {
                   4588:             $items.= &escape($key).'='.&escape($value).'&';
                   4589:         }
                   4590:     }
                   4591:     $items=~s/\&$//;
1.627     albertel 4592:     if ($critical) {
                   4593: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4594:     } else {
                   4595: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4596:     }
1.449     matthew  4597: }
                   4598: 
1.12      www      4599: # --------------------------------------------------------------- put interface
                   4600: 
                   4601: sub put {
1.134     albertel 4602:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4603:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4604:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4605:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4606:    my $items='';
1.800     albertel 4607:    foreach my $item (keys(%$storehash)) {
                   4608:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4609:    }
1.12      www      4610:    $items=~s/\&$//;
1.134     albertel 4611:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4612: }
                   4613: 
1.631     albertel 4614: # ------------------------------------------------------------ newput interface
                   4615: 
                   4616: sub newput {
                   4617:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4618:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4619:    if (!$uname) { $uname=$env{'user.name'}; }
                   4620:    my $uhome=&homeserver($uname,$udomain);
                   4621:    my $items='';
                   4622:    foreach my $key (keys(%$storehash)) {
                   4623:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4624:    }
                   4625:    $items=~s/\&$//;
                   4626:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4627: }
                   4628: 
                   4629: # ---------------------------------------------------------  putstore interface
                   4630: 
1.524     raeburn  4631: sub putstore {
1.715     albertel 4632:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4633:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4634:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4635:    my $uhome=&homeserver($uname,$udomain);
                   4636:    my $items='';
1.715     albertel 4637:    foreach my $key (keys(%$storehash)) {
                   4638:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4639:    }
1.715     albertel 4640:    $items=~s/\&$//;
1.716     albertel 4641:    my $esc_symb=&escape($symb);
                   4642:    my $esc_v=&escape($version);
1.715     albertel 4643:    my $reply =
1.716     albertel 4644:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4645: 	      $uhome);
                   4646:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4647:        # gfall back to way things use to be done
1.715     albertel 4648:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4649: 			    $uname);
1.524     raeburn  4650:    }
1.715     albertel 4651:    return $reply;
                   4652: }
                   4653: 
                   4654: sub old_putstore {
1.716     albertel 4655:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4656:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4657:     if (!$uname) { $uname=$env{'user.name'}; }
                   4658:     my $uhome=&homeserver($uname,$udomain);
                   4659:     my %newstorehash;
1.800     albertel 4660:     foreach my $item (keys(%$storehash)) {
                   4661: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4662: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4663:     }
                   4664:     my $items='';
                   4665:     my %allitems = ();
1.800     albertel 4666:     foreach my $item (keys(%newstorehash)) {
                   4667: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4668: 	    my $key = $1.':keys:'.$2;
                   4669: 	    $allitems{$key} .= $3.':';
                   4670: 	}
1.800     albertel 4671: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4672:     }
1.800     albertel 4673:     foreach my $item (keys(%allitems)) {
                   4674: 	$allitems{$item} =~ s/\:$//;
                   4675: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4676:     }
                   4677:     $items=~s/\&$//;
                   4678:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4679: }
                   4680: 
1.47      www      4681: # ------------------------------------------------------ critical put interface
                   4682: 
                   4683: sub cput {
1.134     albertel 4684:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4685:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4686:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4687:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4688:    my $items='';
1.800     albertel 4689:    foreach my $item (keys(%$storehash)) {
                   4690:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4691:    }
1.47      www      4692:    $items=~s/\&$//;
1.134     albertel 4693:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4694: }
                   4695: 
                   4696: # -------------------------------------------------------------- eget interface
                   4697: 
                   4698: sub eget {
1.133     albertel 4699:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4700:    my $items='';
1.800     albertel 4701:    foreach my $item (@$storearr) {
                   4702:        $items.=&escape($item).'&';
1.191     harris41 4703:    }
1.12      www      4704:    $items=~s/\&$//;
1.620     albertel 4705:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4706:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4707:    my $uhome=&homeserver($uname,$udomain);
                   4708:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4709:    my @pairs=split(/\&/,$rep);
                   4710:    my %returnhash=();
1.42      www      4711:    my $i=0;
1.800     albertel 4712:    foreach my $item (@$storearr) {
                   4713:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4714:       $i++;
1.191     harris41 4715:    }
1.12      www      4716:    return %returnhash;
                   4717: }
                   4718: 
1.667     albertel 4719: # ------------------------------------------------------------ tmpput interface
                   4720: sub tmpput {
1.802     raeburn  4721:     my ($storehash,$server,$context)=@_;
1.667     albertel 4722:     my $items='';
1.800     albertel 4723:     foreach my $item (keys(%$storehash)) {
                   4724: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4725:     }
                   4726:     $items=~s/\&$//;
1.802     raeburn  4727:     if (defined($context)) {
                   4728:         $items .= ':'.&escape($context);
                   4729:     }
1.667     albertel 4730:     return &reply("tmpput:$items",$server);
                   4731: }
                   4732: 
                   4733: # ------------------------------------------------------------ tmpget interface
                   4734: sub tmpget {
1.688     albertel 4735:     my ($token,$server)=@_;
                   4736:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4737:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4738:     my %returnhash;
                   4739:     foreach my $item (split(/\&/,$rep)) {
                   4740: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4741:         next if ($key =~ /^error: 2 /);
1.667     albertel 4742: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4743:     }
                   4744:     return %returnhash;
                   4745: }
                   4746: 
1.688     albertel 4747: # ------------------------------------------------------------ tmpget interface
                   4748: sub tmpdel {
                   4749:     my ($token,$server)=@_;
                   4750:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4751:     return &reply("tmpdel:$token",$server);
                   4752: }
                   4753: 
1.765     albertel 4754: # -------------------------------------------------- portfolio access checking
                   4755: 
                   4756: sub portfolio_access {
1.766     albertel 4757:     my ($requrl) = @_;
1.765     albertel 4758:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4759:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4760:     if ($result) {
                   4761:         my %setters;
                   4762:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4763:             my ($startblock,$endblock) =
                   4764:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4765:             if ($startblock && $endblock) {
                   4766:                 return 'B';
                   4767:             }
                   4768:         } else {
                   4769:             my ($startblock,$endblock) =
                   4770:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4771:             if ($startblock && $endblock) {
                   4772:                 return 'B';
                   4773:             }
                   4774:         }
                   4775:     }
1.765     albertel 4776:     if ($result eq 'ok') {
1.766     albertel 4777:        return 'F';
1.765     albertel 4778:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4779:        return 'A';
1.765     albertel 4780:     }
1.766     albertel 4781:     return '';
1.765     albertel 4782: }
                   4783: 
                   4784: sub get_portfolio_access {
1.767     albertel 4785:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4786: 
                   4787:     if (!ref($access_hash)) {
                   4788: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4789: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4790: 						   $file_name);
                   4791: 	$access_hash = $access_controls{$file_name};
                   4792:     }
                   4793: 
1.765     albertel 4794:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4795:     my $now = time;
                   4796:     if (ref($access_hash) eq 'HASH') {
                   4797:         foreach my $key (keys(%{$access_hash})) {
                   4798:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4799:             if ($start > $now) {
                   4800:                 next;
                   4801:             }
                   4802:             if ($end && $end<$now) {
                   4803:                 next;
                   4804:             }
                   4805:             if ($scope eq 'public') {
                   4806:                 $public = $key;
                   4807:                 last;
                   4808:             } elsif ($scope eq 'guest') {
                   4809:                 $guest = $key;
                   4810:             } elsif ($scope eq 'domains') {
                   4811:                 push(@domains,$key);
                   4812:             } elsif ($scope eq 'users') {
                   4813:                 push(@users,$key);
                   4814:             } elsif ($scope eq 'course') {
                   4815:                 push(@courses,$key);
                   4816:             } elsif ($scope eq 'group') {
                   4817:                 push(@groups,$key);
                   4818:             }
                   4819:         }
                   4820:         if ($public) {
                   4821:             return 'ok';
                   4822:         }
                   4823:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4824:             if ($guest) {
                   4825:                 return $guest;
                   4826:             }
                   4827:         } else {
                   4828:             if (@domains > 0) {
                   4829:                 foreach my $domkey (@domains) {
                   4830:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4831:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4832:                             return 'ok';
                   4833:                         }
                   4834:                     }
                   4835:                 }
                   4836:             }
                   4837:             if (@users > 0) {
                   4838:                 foreach my $userkey (@users) {
1.865     raeburn  4839:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4840:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4841:                             if (ref($item) eq 'HASH') {
                   4842:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4843:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4844:                                     return 'ok';
                   4845:                                 }
                   4846:                             }
                   4847:                         }
                   4848:                     } 
1.765     albertel 4849:                 }
                   4850:             }
                   4851:             my %roleshash;
                   4852:             my @courses_and_groups = @courses;
                   4853:             push(@courses_and_groups,@groups); 
                   4854:             if (@courses_and_groups > 0) {
                   4855:                 my (%allgroups,%allroles); 
                   4856:                 my ($start,$end,$role,$sec,$group);
                   4857:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4858:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4859:                         my $cid = $2.'_'.$3; 
                   4860:                         if ($1 eq 'gr') {
                   4861:                             $group = $4;
                   4862:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4863:                         } else {
                   4864:                             if ($4 eq '') {
                   4865:                                 $sec = 'none';
                   4866:                             } else {
                   4867:                                 $sec = $4;
                   4868:                             }
                   4869:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4870:                         }
1.811     albertel 4871:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4872:                         my $cid = $2.'_'.$3;
                   4873:                         if ($4 eq '') {
                   4874:                             $sec = 'none';
                   4875:                         } else {
                   4876:                             $sec = $4;
                   4877:                         }
                   4878:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4879:                     }
                   4880:                 }
                   4881:                 if (keys(%allroles) == 0) {
                   4882:                     return;
                   4883:                 }
                   4884:                 foreach my $key (@courses_and_groups) {
                   4885:                     my %content = %{$$access_hash{$key}};
                   4886:                     my $cnum = $content{'number'};
                   4887:                     my $cdom = $content{'domain'};
                   4888:                     my $cid = $cdom.'_'.$cnum;
                   4889:                     if (!exists($allroles{$cid})) {
                   4890:                         next;
                   4891:                     }    
                   4892:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4893:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4894:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4895:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4896:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4897:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4898:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4899:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4900:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4901:                                         if (grep/^all$/,@sections) {
                   4902:                                             return 'ok';
                   4903:                                         } else {
                   4904:                                             if (grep/^$sec$/,@sections) {
                   4905:                                                 return 'ok';
                   4906:                                             }
                   4907:                                         }
                   4908:                                     }
                   4909:                                 }
                   4910:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4911:                                     if (grep/^none$/,@groups) {
                   4912:                                         return 'ok';
                   4913:                                     }
                   4914:                                 } else {
                   4915:                                     if (grep/^all$/,@groups) {
                   4916:                                         return 'ok';
                   4917:                                     } 
                   4918:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4919:                                         if (grep/^$group$/,@groups) {
                   4920:                                             return 'ok';
                   4921:                                         }
                   4922:                                     }
                   4923:                                 } 
                   4924:                             }
                   4925:                         }
                   4926:                     }
                   4927:                 }
                   4928:             }
                   4929:             if ($guest) {
                   4930:                 return $guest;
                   4931:             }
                   4932:         }
                   4933:     }
                   4934:     return;
                   4935: }
                   4936: 
                   4937: sub course_group_datechecker {
                   4938:     my ($dates,$now,$status) = @_;
                   4939:     my ($start,$end) = split(/\./,$dates);
                   4940:     if (!$start && !$end) {
                   4941:         return 'ok';
                   4942:     }
                   4943:     if (grep/^active$/,@{$status}) {
                   4944:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4945:             return 'ok';
                   4946:         }
                   4947:     }
                   4948:     if (grep/^previous$/,@{$status}) {
                   4949:         if ($end > $now ) {
                   4950:             return 'ok';
                   4951:         }
                   4952:     }
                   4953:     if (grep/^future$/,@{$status}) {
                   4954:         if ($start > $now) {
                   4955:             return 'ok';
                   4956:         }
                   4957:     }
                   4958:     return; 
                   4959: }
                   4960: 
                   4961: sub parse_portfolio_url {
                   4962:     my ($url) = @_;
                   4963: 
                   4964:     my ($type,$udom,$unum,$group,$file_name);
                   4965:     
1.823     albertel 4966:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4967: 	$type = 1;
                   4968:         $udom = $1;
                   4969:         $unum = $2;
                   4970:         $file_name = $3;
1.823     albertel 4971:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4972: 	$type = 2;
                   4973:         $udom = $1;
                   4974:         $unum = $2;
                   4975:         $group = $3;
                   4976:         $file_name = $3.'/'.$4;
                   4977:     }
                   4978:     if (wantarray) {
                   4979: 	return ($type,$udom,$unum,$file_name,$group);
                   4980:     }
                   4981:     return $type;
                   4982: }
                   4983: 
                   4984: sub is_portfolio_url {
                   4985:     my ($url) = @_;
                   4986:     return scalar(&parse_portfolio_url($url));
                   4987: }
                   4988: 
1.798     raeburn  4989: sub is_portfolio_file {
                   4990:     my ($file) = @_;
1.820     raeburn  4991:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4992:         return 1;
                   4993:     }
                   4994:     return;
                   4995: }
                   4996: 
1.976     raeburn  4997: sub usertools_access {
1.985     raeburn  4998:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4999:     my ($access,%tools);
                   5000:     if ($context eq '') {
                   5001:         $context = 'tools';
                   5002:     }
                   5003:     if ($context eq 'requestcourses') {
                   5004:         %tools = (
                   5005:                       official   => 1,
                   5006:                       unofficial => 1,
1.1006    raeburn  5007:                       community  => 1,
1.985     raeburn  5008:                  );
                   5009:     } else {
                   5010:         %tools = (
                   5011:                       aboutme   => 1,
                   5012:                       blog      => 1,
                   5013:                       portfolio => 1,
                   5014:                  );
                   5015:     }
1.976     raeburn  5016:     return if (!defined($tools{$tool}));
                   5017: 
                   5018:     if ((!defined($udom)) || (!defined($uname))) {
                   5019:         $udom = $env{'user.domain'};
                   5020:         $uname = $env{'user.name'};
                   5021:     }
                   5022: 
1.978     raeburn  5023:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5024:         if ($action ne 'reload') {
1.985     raeburn  5025:             if ($context eq 'requestcourses') {
                   5026:                 return $env{'environment.canrequest.'.$tool};
                   5027:             } else {
                   5028:                 return $env{'environment.availabletools.'.$tool};
                   5029:             }
                   5030:         }
1.976     raeburn  5031:     }
                   5032: 
                   5033:     my ($toolstatus,$inststatus);
                   5034: 
1.985     raeburn  5035:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5036:          ($action ne 'reload')) {
                   5037:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5038:         $inststatus = $env{'environment.inststatus'};
                   5039:     } else {
1.1025    raeburn  5040:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  5041:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  5042:         $inststatus = $userenv{'inststatus'};
                   5043:     }
                   5044: 
                   5045:     if ($toolstatus ne '') {
                   5046:         if ($toolstatus) {
                   5047:             $access = 1;
                   5048:         } else {
                   5049:             $access = 0;
                   5050:         }
                   5051:         return $access;
                   5052:     }
                   5053: 
                   5054:     my $is_adv = &is_advanced_user($udom,$uname);
                   5055:     my %domdef = &get_domain_defaults($udom);
                   5056:     if (ref($domdef{$tool}) eq 'HASH') {
                   5057:         if ($is_adv) {
                   5058:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5059:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5060:                     $access = 1;
                   5061:                 } else {
                   5062:                     $access = 0;
                   5063:                 }
                   5064:                 return $access;
                   5065:             }
                   5066:         }
                   5067:         if ($inststatus ne '') {
                   5068:             my ($hasaccess,$hasnoaccess);
                   5069:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5070:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5071:                     if ($domdef{$tool}{$affiliation}) {
                   5072:                         $hasaccess = 1;
                   5073:                     } else {
                   5074:                         $hasnoaccess = 1;
                   5075:                     }
                   5076:                 }
                   5077:             }
                   5078:             if ($hasaccess || $hasnoaccess) {
                   5079:                 if ($hasaccess) {
                   5080:                     $access = 1;
                   5081:                 } elsif ($hasnoaccess) {
                   5082:                     $access = 0; 
                   5083:                 }
                   5084:                 return $access;
                   5085:             }
                   5086:         } else {
                   5087:             if ($domdef{$tool}{'default'} ne '') {
                   5088:                 if ($domdef{$tool}{'default'}) {
                   5089:                     $access = 1;
                   5090:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5091:                     $access = 0;
                   5092:                 }
                   5093:                 return $access;
                   5094:             }
                   5095:         }
                   5096:     } else {
1.985     raeburn  5097:         if ($context eq 'tools') {
                   5098:             $access = 1;
                   5099:         } else {
                   5100:             $access = 0;
                   5101:         }
1.976     raeburn  5102:         return $access;
                   5103:     }
                   5104: }
                   5105: 
1.1050    raeburn  5106: sub is_course_owner {
                   5107:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5108:     if (($udom eq '') || ($uname eq '')) {
                   5109:         $udom = $env{'user.domain'};
                   5110:         $uname = $env{'user.name'};
                   5111:     }
                   5112:     unless (($udom eq '') || ($uname eq '')) {
                   5113:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5114:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5115:                 return 1;
                   5116:             } else {
                   5117:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5118:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5119:                     return 1;
                   5120:                 }
                   5121:             }
                   5122:         }
                   5123:     }
                   5124:     return;
                   5125: }
                   5126: 
1.976     raeburn  5127: sub is_advanced_user {
                   5128:     my ($udom,$uname) = @_;
                   5129:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5130:     my %allroles;
                   5131:     my $is_adv;
                   5132:     foreach my $role (keys(%roleshash)) {
                   5133:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5134:         my $area = '/'.$tdomain.'/'.$trest;
                   5135:         if ($sec ne '') {
                   5136:             $area .= '/'.$sec;
                   5137:         }
                   5138:         if (($area ne '') && ($trole ne '')) {
                   5139:             my $spec=$trole.'.'.$area;
                   5140:             if ($trole =~ /^cr\//) {
                   5141:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5142:             } elsif ($trole ne 'gr') {
                   5143:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5144:             }
                   5145:         }
                   5146:     }
                   5147:     foreach my $role (keys(%allroles)) {
                   5148:         last if ($is_adv);
                   5149:         foreach my $item (split(/:/,$allroles{$role})) {
                   5150:             if ($item ne '') {
                   5151:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5152:                 if ($privilege eq 'adv') {
                   5153:                     $is_adv = 1;
                   5154:                     last;
                   5155:                 }
                   5156:             }
                   5157:         }
                   5158:     }
                   5159:     return $is_adv;
                   5160: }
1.798     raeburn  5161: 
1.1035    raeburn  5162: sub check_can_request {
1.1036    raeburn  5163:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5164:     my $canreq = 0;
                   5165:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5166:     my @options = ('approval','validate','autolimit');
                   5167:     my $optregex = join('|',@options);
                   5168:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5169:         foreach my $type (@{$types}) {
                   5170:             if (&usertools_access($env{'user.name'},
                   5171:                                   $env{'user.domain'},
                   5172:                                   $type,undef,'requestcourses')) {
                   5173:                 $canreq ++;
1.1036    raeburn  5174:                 if (ref($request_domains) eq 'HASH') {
                   5175:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5176:                 }
1.1035    raeburn  5177:                 if ($dom eq $env{'user.domain'}) {
                   5178:                     $can_request->{$type} = 1;
                   5179:                 }
                   5180:             }
                   5181:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5182:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5183:                 if (@curr > 0) {
1.1036    raeburn  5184:                     foreach my $item (@curr) {
                   5185:                         if (ref($request_domains) eq 'HASH') {
                   5186:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5187:                             if ($otherdom ne '') {
                   5188:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5189:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5190:                                         push(@{$request_domains->{$type}},$otherdom);
                   5191:                                     }
                   5192:                                 } else {
                   5193:                                     push(@{$request_domains->{$type}},$otherdom);
                   5194:                                 }
                   5195:                             }
                   5196:                         }
                   5197:                     }
                   5198:                     unless($dom eq $env{'user.domain'}) {
                   5199:                         $canreq ++;
1.1035    raeburn  5200:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5201:                             $can_request->{$type} = 1;
                   5202:                         }
                   5203:                     }
                   5204:                 }
                   5205:             }
                   5206:         }
                   5207:     }
                   5208:     return $canreq;
                   5209: }
                   5210: 
1.341     www      5211: # ---------------------------------------------- Custom access rule evaluation
                   5212: 
                   5213: sub customaccess {
                   5214:     my ($priv,$uri)=@_;
1.807     albertel 5215:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5216:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5217:     $udom = &LONCAPA::clean_domain($udom);
                   5218:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5219:     my $access=0;
1.800     albertel 5220:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5221: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5222: 	if ($type eq 'user') {
                   5223: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5224: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5225: 		if ($tdom) {
                   5226: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5227: 		}
1.896     albertel 5228: 		if ($tuname) {
                   5229: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5230: 		}
                   5231: 		$access=($effect eq 'allow');
                   5232: 		last;
                   5233: 	    }
                   5234: 	} else {
                   5235: 	    if ($role) {
                   5236: 		if ($role ne $urole) { next; }
                   5237: 	    }
                   5238: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5239: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5240: 		if ($tdom) {
                   5241: 		    if ($tdom ne $udom) { next; }
                   5242: 		}
                   5243: 		if ($tcrs) {
                   5244: 		    if ($tcrs ne $ucrs) { next; }
                   5245: 		}
                   5246: 		if ($tsec) {
                   5247: 		    if ($tsec ne $usec) { next; }
                   5248: 		}
                   5249: 		$access=($effect eq 'allow');
                   5250: 		last;
                   5251: 	    }
                   5252: 	    if ($realm eq '' && $role eq '') {
                   5253: 		$access=($effect eq 'allow');
                   5254: 	    }
1.402     bowersj2 5255: 	}
1.341     www      5256:     }
                   5257:     return $access;
                   5258: }
                   5259: 
1.103     harris41 5260: # ------------------------------------------------- Check for a user privilege
1.12      www      5261: 
                   5262: sub allowed {
1.810     raeburn  5263:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5264:     my $ver_orguri=$uri;
1.439     www      5265:     $uri=&deversion($uri);
1.152     www      5266:     my $orguri=$uri;
1.52      www      5267:     $uri=&declutter($uri);
1.809     raeburn  5268: 
1.810     raeburn  5269:     if ($priv eq 'evb') {
                   5270: # Evade communication block restrictions for specified role in a course
                   5271:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5272:             return $1;
                   5273:         } else {
                   5274:             return;
                   5275:         }
                   5276:     }
                   5277: 
1.620     albertel 5278:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5279: # Free bre access to adm and meta resources
1.775     albertel 5280:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5281: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5282: 	&& ($priv eq 'bre')) {
1.14      www      5283: 	return 'F';
1.159     www      5284:     }
                   5285: 
1.545     banghart 5286: # Free bre access to user's own portfolio contents
1.714     raeburn  5287:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5288:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5289: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5290:         my %setters;
                   5291:         my ($startblock,$endblock) = 
                   5292:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5293:         if ($startblock && $endblock) {
                   5294:             return 'B';
                   5295:         } else {
                   5296:             return 'F';
                   5297:         }
1.545     banghart 5298:     }
                   5299: 
1.762     raeburn  5300: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5301:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5302:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5303:         if (exists($env{'request.course.id'})) {
                   5304:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5305:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5306:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5307:                 my $courseprivid=$env{'request.course.id'};
                   5308:                 $courseprivid=~s/\_/\//;
                   5309:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5310:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5311:                     return $1; 
1.762     raeburn  5312:                 } else {
                   5313:                     if ($env{'request.course.sec'}) {
                   5314:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5315:                     }
                   5316:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5317:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5318:                         return $2;
                   5319:                     }
1.714     raeburn  5320:                 }
                   5321:             }
                   5322:         }
                   5323:     }
                   5324: 
1.159     www      5325: # Free bre to public access
                   5326: 
                   5327:     if ($priv eq 'bre') {
1.238     www      5328:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5329: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5330:            return 'F'; 
                   5331:         }
1.238     www      5332:         if ($copyright eq 'priv') {
                   5333:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5334: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5335: 		return '';
                   5336:             }
                   5337:         }
                   5338:         if ($copyright eq 'domain') {
                   5339:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5340: 	    unless (($env{'user.domain'} eq $1) ||
                   5341:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5342: 		return '';
                   5343:             }
1.262     matthew  5344:         }
1.620     albertel 5345:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5346:             # Library role, so allow browsing of resources in this domain.
                   5347:             return 'F';
1.238     www      5348:         }
1.341     www      5349:         if ($copyright eq 'custom') {
                   5350: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5351:         }
1.14      www      5352:     }
1.264     matthew  5353:     # Domain coordinator is trying to create a course
1.620     albertel 5354:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5355:         # uri is the requested domain in this case.
                   5356:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5357:         # a role of dc for the domain in question.
1.620     albertel 5358:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5359:     }
1.29      www      5360: 
1.52      www      5361:     my $thisallowed='';
                   5362:     my $statecond=0;
                   5363:     my $courseprivid='';
                   5364: 
1.1039    raeburn  5365:     my $ownaccess;
1.1043    raeburn  5366:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5367:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5368:         if ($uri eq '') {
                   5369:             $ownaccess = 1;
                   5370:         } else {
                   5371:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5372:                 my $udom = $env{'user.domain'};
                   5373:                 my $uname = $env{'user.name'};
                   5374:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5375:                     $ownaccess = 1;
1.1040    raeburn  5376:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5377:                     unless ($uri =~ m{\.\./}) {
                   5378:                         $ownaccess = 1;
                   5379:                     }
                   5380:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5381:                     my $now = time;
                   5382:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5383:                         my $adom = $1;
                   5384:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5385:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5386:                                 my ($start,$end) = split('.',$env{$key});
                   5387:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5388:                                     $ownaccess = 1;
                   5389:                                     last;
                   5390:                                 }
                   5391:                             }
                   5392:                         }
                   5393:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5394:                         my $adom = $1;
                   5395:                         my $aname = $2;
1.1042    raeburn  5396:                         foreach my $role ('ca','aa') { 
                   5397:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5398:                                 my ($start,$end) =
                   5399:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5400:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5401:                                     $ownaccess = 1;
                   5402:                                     last;
                   5403:                                 }
1.1039    raeburn  5404:                             }
                   5405:                         }
                   5406:                     }
                   5407:                 }
                   5408:             }
                   5409:         }
                   5410:     }
                   5411: 
1.52      www      5412: # Course
                   5413: 
1.620     albertel 5414:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5415:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5416:             $thisallowed.=$1;
                   5417:         }
1.52      www      5418:     }
1.29      www      5419: 
1.52      www      5420: # Domain
                   5421: 
1.620     albertel 5422:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5423:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5424:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5425:             $thisallowed.=$1;
                   5426:         }
1.12      www      5427:     }
1.52      www      5428: 
                   5429: # Course: uri itself is a course
1.66      www      5430:     my $courseuri=$uri;
                   5431:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5432:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5433: 
1.620     albertel 5434:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5435:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5436:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5437:             $thisallowed.=$1;
                   5438:         }
1.12      www      5439:     }
1.29      www      5440: 
1.665     albertel 5441: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5442: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5443:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5444: 	$thisallowed='';
1.671     raeburn  5445:         my ($match)=&is_on_map($uri);
                   5446:         if ($match) {
                   5447:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5448:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5449:                 $thisallowed.=$1;
                   5450:             }
                   5451:         } else {
1.705     albertel 5452:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5453:             if ($refuri) {
                   5454:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5455:                     $thisallowed='F';
1.671     raeburn  5456:                 } else {
                   5457:                     $refuri=&declutter($refuri);
                   5458:                     my ($match) = &is_on_map($refuri);
                   5459:                     if ($match) {
                   5460:                         $thisallowed='F';
                   5461:                     }
1.669     raeburn  5462:                 }
1.671     raeburn  5463:             }
                   5464:         }
1.314     www      5465:     }
1.492     albertel 5466: 
1.766     albertel 5467:     if ($priv eq 'bre'
                   5468: 	&& $thisallowed ne 'F' 
                   5469: 	&& $thisallowed ne '2'
                   5470: 	&& &is_portfolio_url($uri)) {
                   5471: 	$thisallowed = &portfolio_access($uri);
                   5472:     }
                   5473:     
1.52      www      5474: # Full access at system, domain or course-wide level? Exit.
1.29      www      5475:     if ($thisallowed=~/F/) {
                   5476: 	return 'F';
                   5477:     }
                   5478: 
1.52      www      5479: # If this is generating or modifying users, exit with special codes
1.29      www      5480: 
1.643     www      5481:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5482: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5483: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5484: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5485: 	    unless ($auname) { return $thisallowed; }
                   5486: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5487: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5488: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5489: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5490: 	}
1.52      www      5491: 	return $thisallowed;
                   5492:     }
                   5493: #
1.103     harris41 5494: # Gathered so far: system, domain and course wide privileges
1.52      www      5495: #
                   5496: # Course: See if uri or referer is an individual resource that is part of 
                   5497: # the course
                   5498: 
1.620     albertel 5499:     if ($env{'request.course.id'}) {
1.232     www      5500: 
1.620     albertel 5501:        $courseprivid=$env{'request.course.id'};
                   5502:        if ($env{'request.course.sec'}) {
                   5503:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5504:        }
                   5505:        $courseprivid=~s/\_/\//;
                   5506:        my $checkreferer=1;
1.232     www      5507:        my ($match,$cond)=&is_on_map($uri);
                   5508:        if ($match) {
                   5509:            $statecond=$cond;
1.620     albertel 5510:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5511:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5512:                $thisallowed.=$1;
                   5513:                $checkreferer=0;
                   5514:            }
1.29      www      5515:        }
1.83      www      5516:        
1.148     www      5517:        if ($checkreferer) {
1.620     albertel 5518: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5519:             unless ($refuri) {
1.800     albertel 5520:                 foreach my $key (keys(%env)) {
                   5521: 		    if ($key=~/^httpref\..*\*/) {
                   5522: 			my $pattern=$key;
1.156     www      5523:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5524:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5525:                         $pattern=~s/\//\\\//g;
1.152     www      5526:                         if ($orguri=~/$pattern/) {
1.800     albertel 5527: 			    $refuri=$env{$key};
1.148     www      5528:                         }
                   5529:                     }
1.191     harris41 5530:                 }
1.148     www      5531:             }
1.232     www      5532: 
1.148     www      5533:          if ($refuri) { 
1.152     www      5534: 	  $refuri=&declutter($refuri);
1.232     www      5535:           my ($match,$cond)=&is_on_map($refuri);
                   5536:             if ($match) {
                   5537:               my $refstatecond=$cond;
1.620     albertel 5538:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5539:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5540:                   $thisallowed.=$1;
1.53      www      5541:                   $uri=$refuri;
                   5542:                   $statecond=$refstatecond;
1.52      www      5543:               }
                   5544:           }
1.148     www      5545:         }
1.29      www      5546:        }
1.52      www      5547:    }
1.29      www      5548: 
1.52      www      5549: #
1.103     harris41 5550: # Gathered now: all privileges that could apply, and condition number
1.52      www      5551: # 
                   5552: #
                   5553: # Full or no access?
                   5554: #
1.29      www      5555: 
1.52      www      5556:     if ($thisallowed=~/F/) {
                   5557: 	return 'F';
                   5558:     }
1.29      www      5559: 
1.52      www      5560:     unless ($thisallowed) {
                   5561:         return '';
                   5562:     }
1.29      www      5563: 
1.52      www      5564: # Restrictions exist, deal with them
                   5565: #
                   5566: #   C:according to course preferences
                   5567: #   R:according to resource settings
                   5568: #   L:unless locked
                   5569: #   X:according to user session state
                   5570: #
                   5571: 
                   5572: # Possibly locked functionality, check all courses
1.54      www      5573: # Locks might take effect only after 10 minutes cache expiration for other
                   5574: # courses, and 2 minutes for current course
1.52      www      5575: 
                   5576:     my $envkey;
                   5577:     if ($thisallowed=~/L/) {
1.1000    raeburn  5578:         foreach $envkey (keys(%env)) {
1.54      www      5579:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5580:                my $courseid=$2;
                   5581:                my $roleid=$1.'.'.$2;
1.92      www      5582:                $courseid=~s/^\///;
1.54      www      5583:                my $expiretime=600;
1.620     albertel 5584:                if ($env{'request.role'} eq $roleid) {
1.54      www      5585: 		  $expiretime=120;
                   5586:                }
                   5587: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5588:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5589:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5590: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5591:                }
1.620     albertel 5592:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5593:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5594: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5595:                        &log($env{'user.domain'},$env{'user.name'},
                   5596:                             $env{'user.home'},
1.57      www      5597:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5598:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5599:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5600: 		       return '';
                   5601:                    }
                   5602:                }
1.620     albertel 5603:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5604:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5605: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5606:                        &log($env{'user.domain'},$env{'user.name'},
                   5607:                             $env{'user.home'},
1.57      www      5608:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5609:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5610:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5611: 		       return '';
                   5612:                    }
                   5613:                }
                   5614: 	   }
1.29      www      5615:        }
1.52      www      5616:     }
                   5617:    
                   5618: #
                   5619: # Rest of the restrictions depend on selected course
                   5620: #
                   5621: 
1.620     albertel 5622:     unless ($env{'request.course.id'}) {
1.766     albertel 5623: 	if ($thisallowed eq 'A') {
                   5624: 	    return 'A';
1.814     raeburn  5625:         } elsif ($thisallowed eq 'B') {
                   5626:             return 'B';
1.766     albertel 5627: 	} else {
                   5628: 	    return '1';
                   5629: 	}
1.52      www      5630:     }
1.29      www      5631: 
1.52      www      5632: #
                   5633: # Now user is definitely in a course
                   5634: #
1.53      www      5635: 
                   5636: 
                   5637: # Course preferences
                   5638: 
                   5639:    if ($thisallowed=~/C/) {
1.620     albertel 5640:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5641:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5642:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5643: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5644: 	   if ($priv ne 'pch') { 
                   5645: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5646: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5647: 			$env{'request.course.id'});
                   5648: 	   }
1.237     www      5649:            return '';
                   5650:        }
                   5651: 
1.620     albertel 5652:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5653: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5654: 	   if ($priv ne 'pch') { 
                   5655: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5656: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5657: 			$env{'request.course.id'});
                   5658: 	   }
1.54      www      5659:            return '';
                   5660:        }
1.53      www      5661:    }
                   5662: 
                   5663: # Resource preferences
                   5664: 
                   5665:    if ($thisallowed=~/R/) {
1.620     albertel 5666:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5667:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5668: 	   if ($priv ne 'pch') { 
                   5669: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5670: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5671: 	   }
                   5672: 	   return '';
1.54      www      5673:        }
1.53      www      5674:    }
1.30      www      5675: 
1.246     www      5676: # Restricted by state or randomout?
1.30      www      5677: 
1.52      www      5678:    if ($thisallowed=~/X/) {
1.620     albertel 5679:       if ($env{'acc.randomout'}) {
1.579     albertel 5680: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5681:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5682:             return ''; 
                   5683:          }
1.247     www      5684:       }
                   5685:       if (&condval($statecond)) {
1.52      www      5686: 	 return '2';
                   5687:       } else {
                   5688:          return '';
                   5689:       }
                   5690:    }
1.30      www      5691: 
1.766     albertel 5692:     if ($thisallowed eq 'A') {
                   5693: 	return 'A';
1.814     raeburn  5694:     } elsif ($thisallowed eq 'B') {
                   5695:         return 'B';
1.766     albertel 5696:     }
1.52      www      5697:    return 'F';
1.232     www      5698: }
                   5699: 
1.710     albertel 5700: sub split_uri_for_cond {
                   5701:     my $uri=&deversion(&declutter(shift));
                   5702:     my @uriparts=split(/\//,$uri);
                   5703:     my $filename=pop(@uriparts);
                   5704:     my $pathname=join('/',@uriparts);
                   5705:     return ($pathname,$filename);
                   5706: }
1.232     www      5707: # --------------------------------------------------- Is a resource on the map?
                   5708: 
                   5709: sub is_on_map {
1.710     albertel 5710:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5711:     #Trying to find the conditional for the file
1.620     albertel 5712:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5713: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5714:     if ($match) {
1.289     bowersj2 5715: 	return (1,$1);
                   5716:     } else {
1.434     www      5717: 	return (0,0);
1.289     bowersj2 5718:     }
1.12      www      5719: }
                   5720: 
1.427     www      5721: # --------------------------------------------------------- Get symb from alias
                   5722: 
                   5723: sub get_symb_from_alias {
                   5724:     my $symb=shift;
                   5725:     my ($map,$resid,$url)=&decode_symb($symb);
                   5726: # Already is a symb
                   5727:     if ($url) { return $symb; }
                   5728: # Must be an alias
                   5729:     my $aliassymb='';
                   5730:     my %bighash;
1.620     albertel 5731:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5732:                             &GDBM_READER(),0640)) {
                   5733:         my $rid=$bighash{'mapalias_'.$symb};
                   5734: 	if ($rid) {
                   5735: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5736: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5737: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5738: 	}
                   5739:         untie %bighash;
                   5740:     }
                   5741:     return $aliassymb;
                   5742: }
                   5743: 
1.12      www      5744: # ----------------------------------------------------------------- Define Role
                   5745: 
                   5746: sub definerole {
                   5747:   if (allowed('mcr','/')) {
                   5748:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5749:     foreach my $role (split(':',$sysrole)) {
                   5750: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5751:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5752:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5753: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5754:                return "refused:s:$crole&$cqual"; 
                   5755:             }
                   5756:         }
1.191     harris41 5757:     }
1.800     albertel 5758:     foreach my $role (split(':',$domrole)) {
                   5759: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5760:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5761:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5762: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5763:                return "refused:d:$crole&$cqual"; 
                   5764:             }
                   5765:         }
1.191     harris41 5766:     }
1.800     albertel 5767:     foreach my $role (split(':',$courole)) {
                   5768: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5769:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5770:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5771: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5772:                return "refused:c:$crole&$cqual"; 
                   5773:             }
                   5774:         }
1.191     harris41 5775:     }
1.620     albertel 5776:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5777:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5778: 	        "rolesdef_$rolename=".
                   5779:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5780:     return reply($command,$env{'user.home'});
1.12      www      5781:   } else {
                   5782:     return 'refused';
                   5783:   }
1.105     harris41 5784: }
                   5785: 
                   5786: # ---------------- Make a metadata query against the network of library servers
                   5787: 
                   5788: sub metadata_query {
1.244     matthew  5789:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5790:     my %rhash;
1.845     albertel 5791:     my %libserv = &all_library();
1.244     matthew  5792:     my @server_list = (defined($server_array) ? @$server_array
                   5793:                                               : keys(%libserv) );
                   5794:     for my $server (@server_list) {
1.118     harris41 5795: 	unless ($custom or $customshow) {
                   5796: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5797: 	    $rhash{$server}=$reply;
                   5798: 	}
                   5799: 	else {
                   5800: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5801: 			     &escape($custom).':'.&escape($customshow),
                   5802: 			     $server);
                   5803: 	    $rhash{$server}=$reply;
                   5804: 	}
1.112     harris41 5805:     }
1.118     harris41 5806:     return \%rhash;
1.240     www      5807: }
                   5808: 
                   5809: # ----------------------------------------- Send log queries and wait for reply
                   5810: 
                   5811: sub log_query {
                   5812:     my ($uname,$udom,$query,%filters)=@_;
                   5813:     my $uhome=&homeserver($uname,$udom);
                   5814:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5815:     my $uhost=&hostname($uhome);
1.800     albertel 5816:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5817:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5818:                        $uhome);
1.479     albertel 5819:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5820:     return get_query_reply($queryid);
                   5821: }
                   5822: 
1.818     raeburn  5823: # -------------------------- Update MySQL table for portfolio file
                   5824: 
                   5825: sub update_portfolio_table {
1.821     raeburn  5826:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5827:     if ($group ne '') {
                   5828:         $file_name =~s /^\Q$group\E//;
                   5829:     }
1.818     raeburn  5830:     my $homeserver = &homeserver($uname,$udom);
                   5831:     my $queryid=
1.821     raeburn  5832:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5833:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5834:     my $reply = &get_query_reply($queryid);
                   5835:     return $reply;
                   5836: }
                   5837: 
1.899     raeburn  5838: # -------------------------- Update MySQL allusers table
                   5839: 
                   5840: sub update_allusers_table {
                   5841:     my ($uname,$udom,$names) = @_;
                   5842:     my $homeserver = &homeserver($uname,$udom);
                   5843:     my $queryid=
                   5844:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5845:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5846:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5847:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5848:                'generation='.&escape($names->{'generation'}).'%%'.
                   5849:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5850:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5851:     return;
1.899     raeburn  5852: }
                   5853: 
1.508     raeburn  5854: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5855: 
                   5856: sub fetch_enrollment_query {
1.511     raeburn  5857:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5858:     my $homeserver;
1.547     raeburn  5859:     my $maxtries = 1;
1.508     raeburn  5860:     if ($context eq 'automated') {
                   5861:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5862:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5863:     } else {
                   5864:         $homeserver = &homeserver($cnum,$dom);
                   5865:     }
1.838     albertel 5866:     my $host=&hostname($homeserver);
1.506     raeburn  5867:     my $cmd = '';
1.1000    raeburn  5868:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5869:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5870:     }
                   5871:     $cmd =~ s/%%$//;
                   5872:     $cmd = &escape($cmd);
                   5873:     my $query = 'fetchenrollment';
1.620     albertel 5874:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5875:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5876:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5877:         return 'error: '.$queryid;
                   5878:     }
1.506     raeburn  5879:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5880:     my $tries = 1;
                   5881:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5882:         $reply = &get_query_reply($queryid);
                   5883:         $tries ++;
                   5884:     }
1.526     raeburn  5885:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5886:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5887:     } else {
1.901     albertel 5888:         my @responses = split(/:/,$reply);
1.515     raeburn  5889:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5890:             foreach my $line (@responses) {
                   5891:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5892:                 $$replyref{$key} = $value;
                   5893:             }
                   5894:         } else {
1.506     raeburn  5895:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5896:             foreach my $line (@responses) {
                   5897:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5898:                 $$replyref{$key} = $value;
                   5899:                 if ($value > 0) {
1.800     albertel 5900:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5901:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5902:                         my $destname = $pathname.'/'.$filename;
                   5903:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5904:                         if ($xml_classlist =~ /^error/) {
                   5905:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5906:                         } else {
1.506     raeburn  5907:                             if ( open(FILE,">$destname") ) {
                   5908:                                 print FILE &unescape($xml_classlist);
                   5909:                                 close(FILE);
1.526     raeburn  5910:                             } else {
                   5911:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5912:                             }
                   5913:                         }
                   5914:                     }
                   5915:                 }
                   5916:             }
                   5917:         }
                   5918:         return 'ok';
                   5919:     }
                   5920:     return 'error';
                   5921: }
                   5922: 
1.242     www      5923: sub get_query_reply {
                   5924:     my $queryid=shift;
1.240     www      5925:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5926:     my $reply='';
                   5927:     for (1..100) {
                   5928: 	sleep 2;
                   5929:         if (-e $replyfile.'.end') {
1.448     albertel 5930: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5931: 		$reply = join('',<$fh>);
                   5932: 		close($fh);
1.240     www      5933: 	   } else { return 'error: reply_file_error'; }
1.242     www      5934:            return &unescape($reply);
                   5935: 	}
1.240     www      5936:     }
1.242     www      5937:     return 'timeout:'.$queryid;
1.240     www      5938: }
                   5939: 
                   5940: sub courselog_query {
1.241     www      5941: #
                   5942: # possible filters:
                   5943: # url: url or symb
                   5944: # username
                   5945: # domain
                   5946: # action: view, submit, grade
                   5947: # start: timestamp
                   5948: # end: timestamp
                   5949: #
1.240     www      5950:     my (%filters)=@_;
1.620     albertel 5951:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5952:     if ($filters{'url'}) {
                   5953: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5954:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5955:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5956:     }
1.620     albertel 5957:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5958:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5959:     return &log_query($cname,$cdom,'courselog',%filters);
                   5960: }
                   5961: 
                   5962: sub userlog_query {
1.858     raeburn  5963: #
                   5964: # possible filters:
                   5965: # action: log check role
                   5966: # start: timestamp
                   5967: # end: timestamp
                   5968: #
1.240     www      5969:     my ($uname,$udom,%filters)=@_;
                   5970:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5971: }
                   5972: 
1.506     raeburn  5973: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5974: 
                   5975: sub auto_run {
1.508     raeburn  5976:     my ($cnum,$cdom) = @_;
1.876     raeburn  5977:     my $response = 0;
                   5978:     my $settings;
                   5979:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5980:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5981:         $settings = $domconfig{'autoenroll'};
                   5982:         if ($settings->{'run'} eq '1') {
                   5983:             $response = 1;
                   5984:         }
                   5985:     } else {
1.934     raeburn  5986:         my $homeserver;
                   5987:         if (&is_course($cdom,$cnum)) {
                   5988:             $homeserver = &homeserver($cnum,$cdom);
                   5989:         } else {
                   5990:             $homeserver = &domain($cdom,'primary');
                   5991:         }
                   5992:         if ($homeserver ne 'no_host') {
                   5993:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5994:         }
1.876     raeburn  5995:     }
1.506     raeburn  5996:     return $response;
                   5997: }
1.776     albertel 5998: 
1.506     raeburn  5999: sub auto_get_sections {
1.508     raeburn  6000:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6001:     my $homeserver;
                   6002:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6003:         $homeserver = &homeserver($cnum,$cdom);
                   6004:     }
                   6005:     if (!defined($homeserver)) { 
                   6006:         if ($cdom =~ /^$match_domain$/) {
                   6007:             $homeserver = &domain($cdom,'primary');
                   6008:         }
                   6009:     }
                   6010:     my @secs;
                   6011:     if (defined($homeserver)) {
                   6012:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6013:         unless ($response eq 'refused') {
                   6014:             @secs = split(/:/,$response);
                   6015:         }
1.506     raeburn  6016:     }
                   6017:     return @secs;
                   6018: }
1.776     albertel 6019: 
1.506     raeburn  6020: sub auto_new_course {
1.508     raeburn  6021:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6022:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6023:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  6024:     return $response;
                   6025: }
1.776     albertel 6026: 
1.506     raeburn  6027: sub auto_validate_courseID {
1.508     raeburn  6028:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6029:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6030:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6031:     return $response;
                   6032: }
1.776     albertel 6033: 
1.1007    raeburn  6034: sub auto_validate_instcode {
1.1020    raeburn  6035:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6036:     my ($homeserver,$response);
                   6037:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6038:         $homeserver = &homeserver($cnum,$cdom);
                   6039:     }
                   6040:     if (!defined($homeserver)) {
                   6041:         if ($cdom =~ /^$match_domain$/) {
                   6042:             $homeserver = &domain($cdom,'primary');
                   6043:         }
                   6044:     }
1.1056.4.2  raeburn  6045:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6046:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6047:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6048:     return ($outcome,$description);
1.1007    raeburn  6049: }
                   6050: 
1.506     raeburn  6051: sub auto_create_password {
1.873     raeburn  6052:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6053:     my ($homeserver,$response);
1.506     raeburn  6054:     my $create_passwd = 0;
                   6055:     my $authchk = '';
1.873     raeburn  6056:     if ($udom =~ /^$match_domain$/) {
                   6057:         $homeserver = &domain($udom,'primary');
                   6058:     }
                   6059:     if ($homeserver eq '') {
                   6060:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6061:             $homeserver = &homeserver($cnum,$cdom);
                   6062:         }
                   6063:     }
                   6064:     if ($homeserver eq '') {
                   6065:         $authchk = 'nodomain';
1.506     raeburn  6066:     } else {
1.873     raeburn  6067:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6068:         if ($response eq 'refused') {
                   6069:             $authchk = 'refused';
                   6070:         } else {
1.901     albertel 6071:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6072:         }
1.506     raeburn  6073:     }
                   6074:     return ($authparam,$create_passwd,$authchk);
                   6075: }
                   6076: 
1.706     raeburn  6077: sub auto_photo_permission {
                   6078:     my ($cnum,$cdom,$students) = @_;
                   6079:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6080:     my ($outcome,$perm_reqd,$conditions) = 
                   6081: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6082:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6083: 	return (undef,undef);
                   6084:     }
1.706     raeburn  6085:     return ($outcome,$perm_reqd,$conditions);
                   6086: }
                   6087: 
                   6088: sub auto_checkphotos {
                   6089:     my ($uname,$udom,$pid) = @_;
                   6090:     my $homeserver = &homeserver($uname,$udom);
                   6091:     my ($result,$resulttype);
                   6092:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6093: 				   &escape($uname).':'.&escape($pid),
                   6094: 				   $homeserver));
1.709     albertel 6095:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6096: 	return (undef,undef);
                   6097:     }
1.706     raeburn  6098:     if ($outcome) {
                   6099:         ($result,$resulttype) = split(/:/,$outcome);
                   6100:     } 
                   6101:     return ($result,$resulttype);
                   6102: }
                   6103: 
                   6104: sub auto_photochoice {
                   6105:     my ($cnum,$cdom) = @_;
                   6106:     my $homeserver = &homeserver($cnum,$cdom);
                   6107:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6108: 						       &escape($cdom),
                   6109: 						       $homeserver)));
1.709     albertel 6110:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6111: 	return (undef,undef);
                   6112:     }
1.706     raeburn  6113:     return ($update,$comment);
                   6114: }
                   6115: 
                   6116: sub auto_photoupdate {
                   6117:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6118:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6119:     my $host=&hostname($homeserver);
1.706     raeburn  6120:     my $cmd = '';
                   6121:     my $maxtries = 1;
1.800     albertel 6122:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6123:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6124:     }
                   6125:     $cmd =~ s/%%$//;
                   6126:     $cmd = &escape($cmd);
                   6127:     my $query = 'institutionalphotos';
                   6128:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6129:     unless ($queryid=~/^\Q$host\E\_/) {
                   6130:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6131:         return 'error: '.$queryid;
                   6132:     }
                   6133:     my $reply = &get_query_reply($queryid);
                   6134:     my $tries = 1;
                   6135:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6136:         $reply = &get_query_reply($queryid);
                   6137:         $tries ++;
                   6138:     }
                   6139:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6140:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6141:     } else {
                   6142:         my @responses = split(/:/,$reply);
                   6143:         my $outcome = shift(@responses); 
                   6144:         foreach my $item (@responses) {
                   6145:             my ($key,$value) = split(/=/,$item);
                   6146:             $$photo{$key} = $value;
                   6147:         }
                   6148:         return $outcome;
                   6149:     }
                   6150:     return 'error';
                   6151: }
                   6152: 
1.521     raeburn  6153: sub auto_instcode_format {
1.793     albertel 6154:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6155: 	$cat_order) = @_;
1.521     raeburn  6156:     my $courses = '';
1.772     raeburn  6157:     my @homeservers;
1.521     raeburn  6158:     if ($caller eq 'global') {
1.841     albertel 6159: 	my %servers = &get_servers($codedom,'library');
                   6160: 	foreach my $tryserver (keys(%servers)) {
                   6161: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6162: 		push(@homeservers,$tryserver);
                   6163: 	    }
1.584     raeburn  6164:         }
1.1022    raeburn  6165:     } elsif ($caller eq 'requests') {
                   6166:         if ($codedom =~ /^$match_domain$/) {
                   6167:             my $chome = &domain($codedom,'primary');
                   6168:             unless ($chome eq 'no_host') {
                   6169:                 push(@homeservers,$chome);
                   6170:             }
                   6171:         }
1.521     raeburn  6172:     } else {
1.772     raeburn  6173:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6174:     }
1.793     albertel 6175:     foreach my $code (keys(%{$instcodes})) {
                   6176:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6177:     }
                   6178:     chop($courses);
1.772     raeburn  6179:     my $ok_response = 0;
                   6180:     my $response;
                   6181:     while (@homeservers > 0 && $ok_response == 0) {
                   6182:         my $server = shift(@homeservers); 
                   6183:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6184:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6185:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6186: 		split(/:/,$response);
1.772     raeburn  6187:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6188:             push(@{$codetitles},&str2array($codetitles_str));
                   6189:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6190:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6191:             $ok_response = 1;
                   6192:         }
                   6193:     }
                   6194:     if ($ok_response) {
1.521     raeburn  6195:         return 'ok';
1.772     raeburn  6196:     } else {
                   6197:         return $response;
1.521     raeburn  6198:     }
                   6199: }
                   6200: 
1.792     raeburn  6201: sub auto_instcode_defaults {
                   6202:     my ($domain,$returnhash,$code_order) = @_;
                   6203:     my @homeservers;
1.841     albertel 6204: 
                   6205:     my %servers = &get_servers($domain,'library');
                   6206:     foreach my $tryserver (keys(%servers)) {
                   6207: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6208: 	    push(@homeservers,$tryserver);
                   6209: 	}
1.792     raeburn  6210:     }
1.841     albertel 6211: 
1.792     raeburn  6212:     my $response;
1.841     albertel 6213:     foreach my $server (@homeservers) {
1.792     raeburn  6214:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6215:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6216: 	
                   6217: 	foreach my $pair (split(/\&/,$response)) {
                   6218: 	    my ($name,$value)=split(/\=/,$pair);
                   6219: 	    if ($name eq 'code_order') {
                   6220: 		@{$code_order} = split(/\&/,&unescape($value));
                   6221: 	    } else {
                   6222: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6223: 	    }
                   6224: 	}
                   6225: 	return 'ok';
1.792     raeburn  6226:     }
1.841     albertel 6227: 
                   6228:     return $response;
1.1003    raeburn  6229: }
                   6230: 
                   6231: sub auto_possible_instcodes {
1.1007    raeburn  6232:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6233:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6234:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6235:         return;
                   6236:     }
1.1003    raeburn  6237:     my (@homeservers,$uhome);
                   6238:     if (defined(&domain($domain,'primary'))) {
                   6239:         $uhome=&domain($domain,'primary');
                   6240:         push(@homeservers,&domain($domain,'primary'));
                   6241:     } else {
                   6242:         my %servers = &get_servers($domain,'library');
                   6243:         foreach my $tryserver (keys(%servers)) {
                   6244:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6245:                 push(@homeservers,$tryserver);
                   6246:             }
                   6247:         }
                   6248:     }
                   6249:     my $response;
                   6250:     foreach my $server (@homeservers) {
                   6251:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6252:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6253:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6254:             split(':',$response);
                   6255:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6256:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6257:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6258:             my ($name,$value)=split('=',$item);
                   6259:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6260:         }
                   6261:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6262:             my ($name,$value)=split('=',$item);
                   6263:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6264:         }
                   6265:         return 'ok';
                   6266:     }
                   6267:     return $response;
                   6268: }
1.792     raeburn  6269: 
1.1010    raeburn  6270: sub auto_courserequest_checks {
                   6271:     my ($dom) = @_;
1.1020    raeburn  6272:     my ($homeserver,%validations);
                   6273:     if ($dom =~ /^$match_domain$/) {
                   6274:         $homeserver = &domain($dom,'primary');
                   6275:     }
                   6276:     unless ($homeserver eq 'no_host') {
                   6277:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6278:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6279:             my @items = split(/&/,$response);
                   6280:             foreach my $item (@items) {
                   6281:                 my ($key,$value) = split('=',$item);
                   6282:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6283:             }
                   6284:         }
                   6285:     }
1.1010    raeburn  6286:     return %validations; 
                   6287: }
                   6288: 
1.1020    raeburn  6289: sub auto_courserequest_validation {
                   6290:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6291:     my ($homeserver,$response);
                   6292:     if ($dom =~ /^$match_domain$/) {
                   6293:         $homeserver = &domain($dom,'primary');
                   6294:     }
                   6295:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6296:           
1.1020    raeburn  6297:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6298:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6299:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6300:                                     $homeserver));
                   6301:     }
                   6302:     return $response;
                   6303: }
                   6304: 
1.777     albertel 6305: sub auto_validate_class_sec {
1.918     raeburn  6306:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6307:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6308:     my $ownerlist;
                   6309:     if (ref($owners) eq 'ARRAY') {
                   6310:         $ownerlist = join(',',@{$owners});
                   6311:     } else {
                   6312:         $ownerlist = $owners;
                   6313:     }
1.773     raeburn  6314:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6315:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6316:     return $response;
                   6317: }
                   6318: 
1.679     raeburn  6319: # ------------------------------------------------------- Course Group routines
                   6320: 
                   6321: sub get_coursegroups {
1.809     raeburn  6322:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6323:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6324: }
                   6325: 
1.679     raeburn  6326: sub modify_coursegroup {
                   6327:     my ($cdom,$cnum,$groupsettings) = @_;
                   6328:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6329: }
                   6330: 
1.809     raeburn  6331: sub toggle_coursegroup_status {
                   6332:     my ($cdom,$cnum,$group,$action) = @_;
                   6333:     my ($from_namespace,$to_namespace);
                   6334:     if ($action eq 'delete') {
                   6335:         $from_namespace = 'coursegroups';
                   6336:         $to_namespace = 'deleted_groups';
                   6337:     } else {
                   6338:         $from_namespace = 'deleted_groups';
                   6339:         $to_namespace = 'coursegroups';
                   6340:     }
                   6341:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6342:     if (my $tmp = &error(%curr_group)) {
                   6343:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6344:         return ('read error',$tmp);
                   6345:     } else {
                   6346:         my %savedsettings = %curr_group; 
1.809     raeburn  6347:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6348:         my $deloutcome;
                   6349:         if ($result eq 'ok') {
1.809     raeburn  6350:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6351:         } else {
                   6352:             return ('write error',$result);
                   6353:         }
                   6354:         if ($deloutcome eq 'ok') {
                   6355:             return 'ok';
                   6356:         } else {
                   6357:             return ('delete error',$deloutcome);
                   6358:         }
                   6359:     }
                   6360: }
                   6361: 
1.679     raeburn  6362: sub modify_group_roles {
1.957     raeburn  6363:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6364:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6365:     my $role = 'gr/'.&escape($userprivs);
                   6366:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6367:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6368:     if ($result eq 'ok') {
                   6369:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6370:     }
1.679     raeburn  6371:     return $result;
                   6372: }
                   6373: 
                   6374: sub modify_coursegroup_membership {
                   6375:     my ($cdom,$cnum,$membership) = @_;
                   6376:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6377:     return $result;
                   6378: }
                   6379: 
1.682     raeburn  6380: sub get_active_groups {
                   6381:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6382:     my $now = time;
                   6383:     my %groups = ();
                   6384:     foreach my $key (keys(%env)) {
1.811     albertel 6385:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6386:             my ($start,$end) = split(/\./,$env{$key});
                   6387:             if (($end!=0) && ($end<$now)) { next; }
                   6388:             if (($start!=0) && ($start>$now)) { next; }
                   6389:             if ($1 eq $cdom && $2 eq $cnum) {
                   6390:                 $groups{$3} = $env{$key} ;
                   6391:             }
                   6392:         }
                   6393:     }
                   6394:     return %groups;
                   6395: }
                   6396: 
1.683     raeburn  6397: sub get_group_membership {
                   6398:     my ($cdom,$cnum,$group) = @_;
                   6399:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6400: }
                   6401: 
                   6402: sub get_users_groups {
                   6403:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6404:     my @usersgroups;
1.683     raeburn  6405:     my $cachetime=1800;
                   6406: 
                   6407:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6408:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6409:     if (defined($cached)) {
1.734     albertel 6410:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6411:     } else {  
                   6412:         $grouplist = '';
1.816     raeburn  6413:         my $courseurl = &courseid_to_courseurl($courseid);
                   6414:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6415:         my $access_end = $env{'course.'.$courseid.
                   6416:                               '.default_enrollment_end_date'};
                   6417:         my $now = time;
                   6418:         foreach my $key (keys(%roleshash)) {
                   6419:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6420:                 my $group = $1;
                   6421:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6422:                     my $start = $2;
                   6423:                     my $end = $1;
                   6424:                     if ($start == -1) { next; } # deleted from group
                   6425:                     if (($start!=0) && ($start>$now)) { next; }
                   6426:                     if (($end!=0) && ($end<$now)) {
                   6427:                         if ($access_end && $access_end < $now) {
                   6428:                             if ($access_end - $end < 86400) {
                   6429:                                 push(@usersgroups,$group);
1.733     raeburn  6430:                             }
                   6431:                         }
1.817     raeburn  6432:                         next;
1.733     raeburn  6433:                     }
1.817     raeburn  6434:                     push(@usersgroups,$group);
1.683     raeburn  6435:                 }
                   6436:             }
                   6437:         }
1.817     raeburn  6438:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6439:         $grouplist = join(':',@usersgroups);
                   6440:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6441:     }
1.733     raeburn  6442:     return @usersgroups;
1.683     raeburn  6443: }
                   6444: 
                   6445: sub devalidate_getgroups_cache {
                   6446:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6447:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6448: 
1.683     raeburn  6449:     my $hashid="$udom:$uname:$courseid";
                   6450:     &devalidate_cache_new('getgroups',$hashid);
                   6451: }
                   6452: 
1.12      www      6453: # ------------------------------------------------------------------ Plain Text
                   6454: 
                   6455: sub plaintext {
1.988     raeburn  6456:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6457:     if ($short =~ m{^cr/}) {
1.758     albertel 6458: 	return (split('/',$short))[-1];
                   6459:     }
1.742     raeburn  6460:     if (!defined($cid)) {
                   6461:         $cid = $env{'request.course.id'};
                   6462:     }
                   6463:     my %rolenames = (
1.1008    raeburn  6464:                       Course    => 'std',
                   6465:                       Community => 'alt1',
1.742     raeburn  6466:                     );
1.1037    raeburn  6467:     if ($cid ne '') {
                   6468:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6469:             unless ($forcedefault) {
                   6470:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6471:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6472:                 return &Apache::lonlocal::mt($roletext);
                   6473:             }
                   6474:         }
                   6475:     }
                   6476:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6477:         (defined($rolenames{$type})) && 
                   6478:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6479:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6480:     } elsif ($cid ne '') {
                   6481:         my $crstype = $env{'course.'.$cid.'.type'};
                   6482:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6483:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6484:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6485:         }
1.742     raeburn  6486:     }
1.1037    raeburn  6487:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6488: }
                   6489: 
                   6490: # ----------------------------------------------------------------- Assign Role
                   6491: 
                   6492: sub assignrole {
1.957     raeburn  6493:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6494:         $context)=@_;
1.21      www      6495:     my $mrole;
                   6496:     if ($role =~ /^cr\//) {
1.393     www      6497:         my $cwosec=$url;
1.811     albertel 6498:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6499: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6500:            my $refused = 1;
                   6501:            if ($context eq 'requestcourses') {
                   6502:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6503:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6504:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6505:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6506:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6507:                            if ($crsenv{'internal.courseowner'} eq
                   6508:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6509:                                $refused = '';
                   6510:                            }
                   6511:                        }
                   6512:                    }
                   6513:                }
                   6514:            }
                   6515:            if ($refused) {
                   6516:                &logthis('Refused custom assignrole: '.
                   6517:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6518:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6519:                return 'refused';
                   6520:            }
1.104     www      6521:         }
1.21      www      6522:         $mrole='cr';
1.678     raeburn  6523:     } elsif ($role =~ /^gr\//) {
                   6524:         my $cwogrp=$url;
1.811     albertel 6525:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6526:         unless (&allowed('mdg',$cwogrp)) {
                   6527:             &logthis('Refused group assignrole: '.
                   6528:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6529:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6530:             return 'refused';
                   6531:         }
                   6532:         $mrole='gr';
1.21      www      6533:     } else {
1.82      www      6534:         my $cwosec=$url;
1.811     albertel 6535:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6536:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6537:             my $refused;
                   6538:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6539:                 if (!(&allowed('c'.$role,$url))) {
                   6540:                     $refused = 1;
                   6541:                 }
                   6542:             } else {
                   6543:                 $refused = 1;
                   6544:             }
1.947     raeburn  6545:             if ($refused) {
1.1045    raeburn  6546:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6547:                 if (!$selfenroll && $context eq 'course') {
                   6548:                     my %crsenv;
                   6549:                     if ($role eq 'cc' || $role eq 'co') {
                   6550:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6551:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6552:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6553:                                 if ($crsenv{'internal.courseowner'} eq 
                   6554:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6555:                                     $refused = '';
                   6556:                                 }
                   6557:                             }
                   6558:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6559:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6560:                                 if ($crsenv{'internal.courseowner'} eq 
                   6561:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6562:                                     $refused = '';
                   6563:                                 }
                   6564:                             }
                   6565:                         }
                   6566:                     }
                   6567:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6568:                     $refused = '';
1.1017    raeburn  6569:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6570:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6571:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6572:                         my $wrongcc;
                   6573:                         if ($cnum =~ /^$match_community$/) {
                   6574:                             $wrongcc = 1 if ($role eq 'cc');
                   6575:                         } else {
                   6576:                             $wrongcc = 1 if ($role eq 'co');
                   6577:                         }
                   6578:                         unless ($wrongcc) {
                   6579:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6580:                             if ($crsenv{'internal.courseowner'} eq 
                   6581:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6582:                                 $refused = '';
                   6583:                             }
1.1017    raeburn  6584:                         }
                   6585:                     }
                   6586:                 }
                   6587:                 if ($refused) {
1.947     raeburn  6588:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6589:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6590: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6591:                     return 'refused';
                   6592:                 }
1.932     raeburn  6593:             }
1.104     www      6594:         }
1.21      www      6595:         $mrole=$role;
                   6596:     }
1.620     albertel 6597:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6598:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6599:     if ($end) { $command.='_'.$end; }
1.21      www      6600:     if ($start) {
                   6601: 	if ($end) { 
1.81      www      6602:            $command.='_'.$start; 
1.21      www      6603:         } else {
1.81      www      6604:            $command.='_0_'.$start;
1.21      www      6605:         }
                   6606:     }
1.739     raeburn  6607:     my $origstart = $start;
                   6608:     my $origend = $end;
1.957     raeburn  6609:     my $delflag;
1.357     www      6610: # actually delete
                   6611:     if ($deleteflag) {
1.373     www      6612: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6613: # modify command to delete the role
1.620     albertel 6614:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6615:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6616: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6617: # set start and finish to negative values for userrolelog
                   6618:            $start=-1;
                   6619:            $end=-1;
1.957     raeburn  6620:            $delflag = 1;
1.357     www      6621:         }
                   6622:     }
                   6623: # send command
1.349     www      6624:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6625: # log new user role if status is ok
1.349     www      6626:     if ($answer eq 'ok') {
1.663     raeburn  6627: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6628: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6629:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6630:         unless ($role =~ /^gr/) {
                   6631:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6632:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6633:         }
1.1053    raeburn  6634:         if ($role eq 'cc') {
                   6635:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6636:         }
1.349     www      6637:     }
                   6638:     return $answer;
1.169     harris41 6639: }
                   6640: 
1.1053    raeburn  6641: sub autoupdate_coowners {
                   6642:     my ($url,$end,$start,$uname,$udom) = @_;
                   6643:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6644:     if (($cdom ne '') && ($cnum ne '')) {
                   6645:         my $now = time;
                   6646:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6647:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6648:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6649:             my $instcode = $coursehash{'internal.coursecode'};
                   6650:             if ($instcode ne '') {
1.1056    raeburn  6651:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6652:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6653:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6654:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6655:                         if ($result eq 'valid') {
                   6656:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6657:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6658:                                     push(@newcoowners,$coowner);
                   6659:                                 }
                   6660:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6661:                                     push(@newcoowners,$uname.':'.$udom);
                   6662:                                 }
                   6663:                                 @newcoowners = sort(@newcoowners);
                   6664:                             } else {
                   6665:                                 push(@newcoowners,$uname.':'.$udom);
                   6666:                             }
                   6667:                         } else {
                   6668:                             if ($coursehash{'internal.co-owners'}) {
                   6669:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6670:                                     unless ($coowner eq $uname.':'.$udom) {
                   6671:                                         push(@newcoowners,$coowner);
                   6672:                                     }
                   6673:                                 }
                   6674:                                 unless (@newcoowners > 0) {
                   6675:                                     $delcoowners = 1;
                   6676:                                     $coowners = '';
                   6677:                                 }
                   6678:                             }
                   6679:                         }
                   6680:                         if (@newcoowners || $delcoowners) {
                   6681:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6682:                                             $delcoowners,@newcoowners);
                   6683:                         }
                   6684:                     }
                   6685:                 }
                   6686:             }
                   6687:         }
                   6688:     }
                   6689: }
                   6690: 
                   6691: sub store_coowners {
                   6692:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6693:     my $cid = $cdom.'_'.$cnum;
                   6694:     my ($coowners,$delresult,$putresult);
                   6695:     if (@newcoowners) {
                   6696:         $coowners = join(',',@newcoowners);
                   6697:         my %coownershash = (
                   6698:                             'internal.co-owners' => $coowners,
                   6699:                            );
                   6700:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6701:         if ($putresult eq 'ok') {
                   6702:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6703:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6704:             }
                   6705:         }
                   6706:     }
                   6707:     if ($delcoowners) {
                   6708:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6709:         if ($delresult eq 'ok') {
                   6710:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6711:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6712:             }
                   6713:         }
                   6714:     }
                   6715:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6716:         my %crsinfo =
                   6717:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6718:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6719:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6720:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6721:         }
                   6722:     }
                   6723: }
                   6724: 
1.169     harris41 6725: # -------------------------------------------------- Modify user authentication
1.197     www      6726: # Overrides without validation
                   6727: 
1.169     harris41 6728: sub modifyuserauth {
                   6729:     my ($udom,$uname,$umode,$upass)=@_;
                   6730:     my $uhome=&homeserver($uname,$udom);
1.197     www      6731:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6732:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6733:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6734:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6735:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6736: 		     &escape($upass),$uhome);
1.620     albertel 6737:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6738:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6739:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6740:     &log($udom,,$uname,$uhome,
1.620     albertel 6741:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6742:                                      $env{'user.name'}.', '.$umode.
1.197     www      6743:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6744:     unless ($reply eq 'ok') {
1.197     www      6745:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6746: 	return 'error: '.$reply;
                   6747:     }   
1.170     harris41 6748:     return 'ok';
1.80      www      6749: }
                   6750: 
1.81      www      6751: # --------------------------------------------------------------- Modify a user
1.80      www      6752: 
1.81      www      6753: sub modifyuser {
1.206     matthew  6754:     my ($udom,    $uname, $uid,
                   6755:         $umode,   $upass, $first,
                   6756:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6757:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6758:     $udom= &LONCAPA::clean_domain($udom);
                   6759:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6760:     my $showcandelete = 'none';
                   6761:     if (ref($candelete) eq 'ARRAY') {
                   6762:         if (@{$candelete} > 0) {
                   6763:             $showcandelete = join(', ',@{$candelete});
                   6764:         }
                   6765:     }
1.81      www      6766:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6767:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6768:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6769:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6770:                                      ' desiredhome not specified'). 
1.620     albertel 6771:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6772:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6773:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6774:     my $newuser;
                   6775:     if ($uhome eq 'no_host') {
                   6776:         $newuser = 1;
                   6777:     }
1.80      www      6778: # ----------------------------------------------------------------- Create User
1.406     albertel 6779:     if (($uhome eq 'no_host') && 
                   6780: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6781:         my $unhome='';
1.844     albertel 6782:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6783:             $unhome = $desiredhome;
1.620     albertel 6784: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6785: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6786:         } else { # load balancing routine for determining $unhome
1.81      www      6787:             my $loadm=10000000;
1.841     albertel 6788: 	    my %servers = &get_servers($udom,'library');
                   6789: 	    foreach my $tryserver (keys(%servers)) {
                   6790: 		my $answer=reply('load',$tryserver);
                   6791: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6792: 		    $loadm=$answer;
                   6793: 		    $unhome=$tryserver;
                   6794: 		}
1.80      www      6795: 	    }
                   6796:         }
                   6797:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6798: 	    return 'error: unable to find a home server for '.$uname.
                   6799:                    ' in domain '.$udom;
1.80      www      6800:         }
                   6801:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6802:                          &escape($upass),$unhome);
                   6803: 	unless ($reply eq 'ok') {
                   6804:             return 'error: '.$reply;
                   6805:         }   
1.230     stredwic 6806:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6807:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6808: 	    return 'error: unable verify users home machine.';
1.80      www      6809:         }
1.209     matthew  6810:     }   # End of creation of new user
1.80      www      6811: # ---------------------------------------------------------------------- Add ID
                   6812:     if ($uid) {
                   6813:        $uid=~tr/A-Z/a-z/;
                   6814:        my %uidhash=&idrget($udom,$uname);
1.196     www      6815:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6816:          && (!$forceid)) {
1.80      www      6817: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6818: 	      return 'error: user id "'.$uid.'" does not match '.
                   6819:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6820:           }
                   6821:        } else {
                   6822: 	  &idput($udom,($uname => $uid));
                   6823:        }
                   6824:     }
                   6825: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6826:     my @tmp=&get('environment',
1.899     raeburn  6827: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6828:                     'permanentemail','inststatus'],
1.134     albertel 6829: 		   $udom,$uname);
1.1056.4.4  raeburn  6830:     my (%names,%oldnames);
1.313     matthew  6831:     if ($tmp[0] =~ m/^error:.*/) { 
                   6832:         %names=(); 
                   6833:     } else {
                   6834:         %names = @tmp;
1.1056.4.4  raeburn  6835:         %oldnames = %names;
1.313     matthew  6836:     }
1.1056.4.6  raeburn  6837: #
1.1056.4.1  raeburn  6838: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6839: # of users did not contain them), do not overwrite existing values
                   6840: # unless field is in $candelete array ref.  
                   6841: #
                   6842: 
                   6843:     my @fields = ('firstname','middlename','lastname','generation',
                   6844:                   'permanentemail','id');
                   6845:     my %newvalues;
                   6846:     if (ref($candelete) eq 'ARRAY') {
                   6847:         foreach my $field (@fields) {
                   6848:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6849:                 if ($field eq 'firstname') {
                   6850:                     $names{$field} = $first;
                   6851:                 } elsif ($field eq 'middlename') {
                   6852:                     $names{$field} = $middle;
                   6853:                 } elsif ($field eq 'lastname') {
                   6854:                     $names{$field} = $last;
                   6855:                 } elsif ($field eq 'generation') { 
                   6856:                     $names{$field} = $gene;
                   6857:                 } elsif ($field eq 'permanentemail') {
                   6858:                     $names{$field} = $email;
                   6859:                 } elsif ($field eq 'id') {
                   6860:                     $names{$field}  = $uid;
                   6861:                 }
                   6862:             }
                   6863:         }
                   6864:     }
1.388     www      6865:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6866:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6867:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6868:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6869:     if ($email) {
                   6870:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6871:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6872:     }
1.899     raeburn  6873:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6874:     if (defined($inststatus)) {
                   6875:         $names{'inststatus'} = '';
                   6876:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6877:         if (ref($usertypes) eq 'HASH') {
                   6878:             my @okstatuses; 
                   6879:             foreach my $item (split(/:/,$inststatus)) {
                   6880:                 if (defined($usertypes->{$item})) {
                   6881:                     push(@okstatuses,$item);  
                   6882:                 }
                   6883:             }
                   6884:             if (@okstatuses) {
                   6885:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6886:             }
                   6887:         }
                   6888:     }
1.1056.4.4  raeburn  6889:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6890:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  6891:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6892:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6893:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6894:     } else {
                   6895:         $logmsg .= ' during self creation';
                   6896:     }
1.1056.4.4  raeburn  6897:     my $changed;
                   6898:     if ($newuser) {
                   6899:         $changed = 1;
                   6900:     } else {
                   6901:         foreach my $field (@fields) {
                   6902:             if ($names{$field} ne $oldnames{$field}) {
                   6903:                 $changed = 1;
                   6904:                 last;
                   6905:             }
                   6906:         }
                   6907:     }
                   6908:     unless ($changed) {
                   6909:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   6910:         &logthis($logmsg);
                   6911:         return 'ok';
                   6912:     }
                   6913:     my $reply = &put('environment', \%names, $udom,$uname);
                   6914:     if ($reply ne 'ok') {
                   6915:         return 'error: '.$reply;
                   6916:     }
                   6917:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   6918:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   6919:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  6920:     &logthis($logmsg);
1.134     albertel 6921:     return 'ok';
1.80      www      6922: }
                   6923: 
1.81      www      6924: # -------------------------------------------------------------- Modify student
1.80      www      6925: 
1.81      www      6926: sub modifystudent {
                   6927:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6928:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6929:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6930:     if (!$cid) {
1.620     albertel 6931: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6932: 	    return 'not_in_class';
                   6933: 	}
1.80      www      6934:     }
                   6935: # --------------------------------------------------------------- Make the user
1.81      www      6936:     my $reply=&modifyuser
1.209     matthew  6937: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6938:          $desiredhome,$email,$inststatus);
1.80      www      6939:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6940:     # This will cause &modify_student_enrollment to get the uid from the
                   6941:     # students environment
                   6942:     $uid = undef if (!$forceid);
1.455     albertel 6943:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6944: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6945:     return $reply;
                   6946: }
                   6947: 
                   6948: sub modify_student_enrollment {
1.957     raeburn  6949:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6950:     my ($cdom,$cnum,$chome);
                   6951:     if (!$cid) {
1.620     albertel 6952: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6953: 	    return 'not_in_class';
                   6954: 	}
1.620     albertel 6955: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6956: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6957:     } else {
                   6958: 	($cdom,$cnum)=split(/_/,$cid);
                   6959:     }
1.620     albertel 6960:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6961:     if (!$chome) {
1.457     raeburn  6962: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6963:     }
1.455     albertel 6964:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6965:     # Make sure the user exists
1.81      www      6966:     my $uhome=&homeserver($uname,$udom);
                   6967:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6968: 	return 'error: no such user';
                   6969:     }
1.297     matthew  6970:     # Get student data if we were not given enough information
                   6971:     if (!defined($first)  || $first  eq '' || 
                   6972:         !defined($last)   || $last   eq '' || 
                   6973:         !defined($uid)    || $uid    eq '' || 
                   6974:         !defined($middle) || $middle eq '' || 
                   6975:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6976:         # They did not supply us with enough data to enroll the student, so
                   6977:         # we need to pick up more information.
1.297     matthew  6978:         my %tmp = &get('environment',
1.294     matthew  6979:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6980:                        ,$udom,$uname);
                   6981: 
1.800     albertel 6982:         #foreach my $key (keys(%tmp)) {
                   6983:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6984:         #}
1.294     matthew  6985:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6986:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6987:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6988:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6989:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6990:     }
1.556     albertel 6991:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6992:     my $reply=cput('classlist',
                   6993: 		   {"$uname:$udom" => 
1.515     raeburn  6994: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6995: 		   $cdom,$cnum);
1.81      www      6996:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6997: 	return 'error: '.$reply;
1.652     albertel 6998:     } else {
                   6999: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7000:     }
1.297     matthew  7001:     # Add student role to user
1.83      www      7002:     my $uurl='/'.$cid;
1.81      www      7003:     $uurl=~s/\_/\//g;
                   7004:     if ($usec) {
                   7005: 	$uurl.='/'.$usec;
                   7006:     }
1.957     raeburn  7007:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7008: }
                   7009: 
1.556     albertel 7010: sub format_name {
                   7011:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7012:     my $name;
                   7013:     if ($first ne 'lastname') {
                   7014: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7015:     } else {
                   7016: 	if ($lastname=~/\S/) {
                   7017: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7018: 	    $name=~s/\s+,/,/;
                   7019: 	} else {
                   7020: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7021: 	}
                   7022:     }
                   7023:     $name=~s/^\s+//;
                   7024:     $name=~s/\s+$//;
                   7025:     $name=~s/\s+/ /g;
                   7026:     return $name;
                   7027: }
                   7028: 
1.84      www      7029: # ------------------------------------------------- Write to course preferences
                   7030: 
                   7031: sub writecoursepref {
                   7032:     my ($courseid,%prefs)=@_;
                   7033:     $courseid=~s/^\///;
                   7034:     $courseid=~s/\_/\//g;
                   7035:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7036:     my $chome=homeserver($cnum,$cdomain);
                   7037:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7038: 	return 'error: no such course';
                   7039:     }
                   7040:     my $cstring='';
1.800     albertel 7041:     foreach my $pref (keys(%prefs)) {
                   7042: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7043:     }
1.84      www      7044:     $cstring=~s/\&$//;
                   7045:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7046: }
                   7047: 
                   7048: # ---------------------------------------------------------- Make/modify course
                   7049: 
                   7050: sub createcourse {
1.741     raeburn  7051:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7052:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7053:     $url=&declutter($url);
                   7054:     my $cid='';
1.1028    raeburn  7055:     if ($context eq 'requestcourses') {
                   7056:         my $can_create = 0;
                   7057:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7058:         if ($udom eq $ownerdom) {
                   7059:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7060:                                   $context)) {
                   7061:                 $can_create = 1;
                   7062:             }
                   7063:         } else {
                   7064:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7065:                                            $category);
                   7066:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7067:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7068:                 if (@curr > 0) {
                   7069:                     my @options = qw(approval validate autolimit);
                   7070:                     my $optregex = join('|',@options);
                   7071:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7072:                         $can_create = 1;
                   7073:                     }
                   7074:                 }
                   7075:             }
                   7076:         }
                   7077:         if ($can_create) {
                   7078:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7079:                 unless (&allowed('ccc',$udom)) {
                   7080:                     return 'refused'; 
                   7081:                 }
1.1017    raeburn  7082:             }
                   7083:         } else {
                   7084:             return 'refused';
                   7085:         }
1.1028    raeburn  7086:     } elsif (!&allowed('ccc',$udom)) {
                   7087:         return 'refused';
1.84      www      7088:     }
1.1011    raeburn  7089: # --------------------------------------------------------------- Get Unique ID
                   7090:     my $uname;
                   7091:     if ($cnum =~ /^$match_courseid$/) {
                   7092:         my $chome=&homeserver($cnum,$udom,'true');
                   7093:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7094:             $uname = $cnum;
                   7095:         } else {
1.1038    raeburn  7096:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7097:         }
                   7098:     } else {
1.1038    raeburn  7099:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7100:     }
                   7101:     return $uname if ($uname =~ /^error/);
                   7102: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7103:     if (!defined($course_server)) {
                   7104:         if (defined(&domain($udom,'primary'))) {
                   7105:             $course_server = &domain($udom,'primary');
                   7106:         } else {
                   7107:             $course_server = $env{'user.home'}; 
                   7108:         }
                   7109:     }
                   7110:     my %host_servers =
                   7111:         &Apache::lonnet::get_servers($udom,'library');
                   7112:     unless ($host_servers{$course_server}) {
                   7113:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7114:     }
1.84      www      7115: # ------------------------------------------------------------- Make the course
                   7116:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7117:                       $course_server);
1.84      www      7118:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7119:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7120:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7121: 	return 'error: no such course';
                   7122:     }
1.271     www      7123: # ----------------------------------------------------------------- Course made
1.516     raeburn  7124: # log existence
1.1029    raeburn  7125:     my $now = time;
1.918     raeburn  7126:     my $newcourse = {
                   7127:                     $udom.'_'.$uname => {
1.921     raeburn  7128:                                      description => $description,
                   7129:                                      inst_code   => $inst_code,
                   7130:                                      owner       => $course_owner,
                   7131:                                      type        => $crstype,
1.1029    raeburn  7132:                                      creator     => $env{'user.name'}.':'.
                   7133:                                                     $env{'user.domain'},
                   7134:                                      created     => $now,
                   7135:                                      context     => $context,
1.918     raeburn  7136:                                                 },
                   7137:                     };
1.921     raeburn  7138:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7139: # set toplevel url
1.271     www      7140:     my $topurl=$url;
                   7141:     unless ($nonstandard) {
                   7142: # ------------------------------------------ For standard courses, make top url
                   7143:         my $mapurl=&clutter($url);
1.278     www      7144:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7145:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7146: <map>
                   7147: <resource id="1" type="start"></resource>
                   7148: <resource id="2" src="$mapurl"></resource>
                   7149: <resource id="3" type="finish"></resource>
                   7150: <link index="1" from="1" to="2"></link>
                   7151: <link index="2" from="2" to="3"></link>
                   7152: </map>
                   7153: ENDINITMAP
                   7154:         $topurl=&declutter(
1.638     albertel 7155:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7156:                           );
                   7157:     }
                   7158: # ----------------------------------------------------------- Write preferences
1.84      www      7159:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7160:                      ('description'              => $description,
                   7161:                       'url'                      => $topurl,
                   7162:                       'internal.creator'         => $env{'user.name'}.':'.
                   7163:                                                     $env{'user.domain'},
                   7164:                       'internal.created'         => $now,
                   7165:                       'internal.creationcontext' => $context)
                   7166:                     );
1.84      www      7167:     return '/'.$udom.'/'.$uname;
                   7168: }
                   7169: 
1.1011    raeburn  7170: # ------------------------------------------------------------------- Create ID
                   7171: sub generate_coursenum {
1.1038    raeburn  7172:     my ($udom,$crstype) = @_;
1.1011    raeburn  7173:     my $domdesc = &domain($udom);
                   7174:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7175:     my $first;
                   7176:     if ($crstype eq 'Community') {
                   7177:         $first = '0';
                   7178:     } else {
                   7179:         $first = int(1+rand(9)); 
                   7180:     } 
                   7181:     my $uname=$first.
1.1011    raeburn  7182:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7183:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7184:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7185: # ----------------------------------------------- Make sure that does not exist
                   7186:     my $uhome=&homeserver($uname,$udom,'true');
                   7187:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7188:         if ($crstype eq 'Community') {
                   7189:             $first = '0';
                   7190:         } else {
                   7191:             $first = int(1+rand(9));
                   7192:         }
                   7193:         $uname=$first.
1.1011    raeburn  7194:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7195:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7196:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7197:         $uhome=&homeserver($uname,$udom,'true');
                   7198:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7199:             return 'error: unable to generate unique course-ID';
                   7200:         }
                   7201:     }
                   7202:     return $uname;
                   7203: }
                   7204: 
1.813     albertel 7205: sub is_course {
                   7206:     my ($cdom,$cnum) = @_;
                   7207:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7208: 				undef,'.');
1.813     albertel 7209:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7210:         return 1;
                   7211:     }
                   7212:     return 0;
                   7213: }
                   7214: 
1.1015    raeburn  7215: sub store_userdata {
                   7216:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7217:     my $result;
1.1016    raeburn  7218:     if ($datakey ne '') {
1.1013    raeburn  7219:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7220:             if ($udom eq '' || $uname eq '') {
                   7221:                 $udom = $env{'user.domain'};
                   7222:                 $uname = $env{'user.name'};
                   7223:             }
                   7224:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7225:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7226:                 $result = 'error: no_host';
                   7227:             } else {
                   7228:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7229:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7230: 
                   7231:                 my $namevalue='';
                   7232:                 foreach my $key (keys(%{$storehash})) {
                   7233:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7234:                 }
                   7235:                 $namevalue=~s/\&$//;
                   7236:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7237:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7238:             }
                   7239:         } else {
                   7240:             $result = 'error: data to store was not a hash reference'; 
                   7241:         }
                   7242:     } else {
                   7243:         $result= 'error: invalid requestkey'; 
                   7244:     }
                   7245:     return $result;
                   7246: }
                   7247: 
1.21      www      7248: # ---------------------------------------------------------- Assign Custom Role
                   7249: 
                   7250: sub assigncustomrole {
1.957     raeburn  7251:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7252:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7253:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7254: }
                   7255: 
                   7256: # ----------------------------------------------------------------- Revoke Role
                   7257: 
                   7258: sub revokerole {
1.957     raeburn  7259:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7260:     my $now=time;
1.965     raeburn  7261:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7262: }
                   7263: 
                   7264: # ---------------------------------------------------------- Revoke Custom Role
                   7265: 
                   7266: sub revokecustomrole {
1.957     raeburn  7267:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7268:     my $now=time;
1.357     www      7269:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7270:            $deleteflag,$selfenroll,$context);
1.17      www      7271: }
                   7272: 
1.533     banghart 7273: # ------------------------------------------------------------ Disk usage
1.535     albertel 7274: sub diskusage {
1.955     raeburn  7275:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7276:     $directorypath =~ s/\/$//;
                   7277:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7278:                        .&escape($getpropath).':'.&escape($uname).':'
                   7279:                        .&escape($udom),homeserver($uname,$udom));
                   7280:     if ($listing eq 'unknown_cmd') {
                   7281:         if ($getpropath) {
                   7282:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7283:         }
                   7284:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7285:     }
1.514     albertel 7286:     return $listing;
1.512     banghart 7287: }
                   7288: 
1.566     banghart 7289: sub is_locked {
                   7290:     my ($file_name, $domain, $user) = @_;
                   7291:     my @check;
                   7292:     my $is_locked;
                   7293:     push @check, $file_name;
1.613     albertel 7294:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7295: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7296:     my ($tmp)=keys(%locked);
                   7297:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7298:     
1.566     banghart 7299:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7300:         $is_locked = 'false';
                   7301:         foreach my $entry (@{$locked{$file_name}}) {
                   7302:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7303:                $is_locked = 'true';
                   7304:                last;
1.745     raeburn  7305:            }
                   7306:        }
1.566     banghart 7307:     } else {
                   7308:         $is_locked = 'false';
                   7309:     }
                   7310: }
                   7311: 
1.759     albertel 7312: sub declutter_portfile {
                   7313:     my ($file) = @_;
1.833     albertel 7314:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7315:     return $file;
                   7316: }
                   7317: 
1.559     banghart 7318: # ------------------------------------------------------------- Mark as Read Only
                   7319: 
                   7320: sub mark_as_readonly {
                   7321:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7322:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7323:     my ($tmp)=keys(%current_permissions);
                   7324:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7325:     foreach my $file (@{$files}) {
1.759     albertel 7326: 	$file = &declutter_portfile($file);
1.561     banghart 7327:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7328:     }
1.613     albertel 7329:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7330:     return;
                   7331: }
                   7332: 
1.572     banghart 7333: # ------------------------------------------------------------Save Selected Files
                   7334: 
                   7335: sub save_selected_files {
                   7336:     my ($user, $path, @files) = @_;
                   7337:     my $filename = $user."savedfiles";
1.573     banghart 7338:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7339:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7340:     foreach my $file (@files) {
1.620     albertel 7341:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7342:     }
                   7343:     foreach my $file (@other_files) {
1.574     banghart 7344:         print (OUT $file."\n");
1.572     banghart 7345:     }
1.574     banghart 7346:     close (OUT);
1.572     banghart 7347:     return 'ok';
                   7348: }
                   7349: 
1.574     banghart 7350: sub clear_selected_files {
                   7351:     my ($user) = @_;
                   7352:     my $filename = $user."savedfiles";
                   7353:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7354:     print (OUT undef);
                   7355:     close (OUT);
                   7356:     return ("ok");    
                   7357: }
                   7358: 
1.572     banghart 7359: sub files_in_path {
                   7360:     my ($user, $path) = @_;
                   7361:     my $filename = $user."savedfiles";
                   7362:     my %return_files;
1.574     banghart 7363:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7364:     while (my $line_in = <IN>) {
1.574     banghart 7365:         chomp ($line_in);
                   7366:         my @paths_and_file = split (m!/!, $line_in);
                   7367:         my $file_part = pop (@paths_and_file);
                   7368:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7369:         $path_part.='/';
                   7370:         my $path_and_file = $path_part.$file_part;
                   7371:         if ($path_part eq $path) {
                   7372:             $return_files{$file_part}= 'selected';
                   7373:         }
                   7374:     }
1.574     banghart 7375:     close (IN);
                   7376:     return (\%return_files);
1.572     banghart 7377: }
                   7378: 
                   7379: # called in portfolio select mode, to show files selected NOT in current directory
                   7380: sub files_not_in_path {
                   7381:     my ($user, $path) = @_;
                   7382:     my $filename = $user."savedfiles";
                   7383:     my @return_files;
                   7384:     my $path_part;
1.800     albertel 7385:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7386:     while (my $line = <IN>) {
1.572     banghart 7387:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7388:         my @paths_and_file = split(m|/|, $line);
                   7389:         my $file_part = pop(@paths_and_file);
                   7390:         chomp($file_part);
                   7391:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7392:         $path_part .= '/';
                   7393:         my $path_and_file = $path_part.$file_part;
                   7394:         if ($path_part ne $path) {
1.800     albertel 7395:             push(@return_files, ($path_and_file));
1.572     banghart 7396:         }
                   7397:     }
1.800     albertel 7398:     close(OUT);
1.574     banghart 7399:     return (@return_files);
1.572     banghart 7400: }
                   7401: 
1.745     raeburn  7402: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7403: 
1.745     raeburn  7404: sub get_portfile_permissions {
                   7405:     my ($domain,$user) = @_;
1.613     albertel 7406:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7407:     my ($tmp)=keys(%current_permissions);
                   7408:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7409:     return \%current_permissions;
                   7410: }
                   7411: 
                   7412: #---------------------------------------------Get portfolio file access controls
                   7413: 
1.749     raeburn  7414: sub get_access_controls {
1.745     raeburn  7415:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7416:     my %access;
                   7417:     my $real_file = $file;
                   7418:     $file =~ s/\.meta$//;
1.745     raeburn  7419:     if (defined($file)) {
1.749     raeburn  7420:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7421:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7422:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7423:             }
                   7424:         }
1.745     raeburn  7425:     } else {
1.749     raeburn  7426:         foreach my $key (keys(%{$current_permissions})) {
                   7427:             if ($key =~ /\0accesscontrol$/) {
                   7428:                 if (defined($group)) {
                   7429:                     if ($key !~ m-^\Q$group\E/-) {
                   7430:                         next;
                   7431:                     }
                   7432:                 }
                   7433:                 my ($fullpath) = split(/\0/,$key);
                   7434:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7435:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7436:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7437:                     }
                   7438:                 }
                   7439:             }
                   7440:         }
                   7441:     }
                   7442:     return %access;
                   7443: }
                   7444: 
                   7445: sub modify_access_controls {
                   7446:     my ($file_name,$changes,$domain,$user)=@_;
                   7447:     my ($outcome,$deloutcome);
                   7448:     my %store_permissions;
                   7449:     my %new_values;
                   7450:     my %new_control;
                   7451:     my %translation;
                   7452:     my @deletions = ();
                   7453:     my $now = time;
                   7454:     if (exists($$changes{'activate'})) {
                   7455:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7456:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7457:             my $numnew = scalar(@newitems);
                   7458:             for (my $i=0; $i<$numnew; $i++) {
                   7459:                 my $newkey = $newitems[$i];
                   7460:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7461:                 if ($newkey =~ /^\d+:/) { 
                   7462:                     $newkey =~ s/^(\d+)/$newid/;
                   7463:                     $translation{$1} = $newid;
                   7464:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7465:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7466:                     $translation{$1} = $newid;
                   7467:                 }
1.749     raeburn  7468:                 $new_values{$file_name."\0".$newkey} = 
                   7469:                                           $$changes{'activate'}{$newitems[$i]};
                   7470:                 $new_control{$newkey} = $now;
                   7471:             }
                   7472:         }
                   7473:     }
                   7474:     my %todelete;
                   7475:     my %changed_items;
                   7476:     foreach my $action ('delete','update') {
                   7477:         if (exists($$changes{$action})) {
                   7478:             if (ref($$changes{$action}) eq 'HASH') {
                   7479:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7480:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7481:                     if ($action eq 'delete') { 
                   7482:                         $todelete{$itemnum} = 1;
                   7483:                     } else {
                   7484:                         $changed_items{$itemnum} = $key;
                   7485:                     }
                   7486:                 }
1.745     raeburn  7487:             }
                   7488:         }
1.749     raeburn  7489:     }
                   7490:     # get lock on access controls for file.
                   7491:     my $lockhash = {
                   7492:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7493:                                                        ':'.$env{'user.domain'},
                   7494:                    }; 
                   7495:     my $tries = 0;
                   7496:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7497:    
                   7498:     while (($gotlock ne 'ok') && $tries <3) {
                   7499:         $tries ++;
                   7500:         sleep 1;
                   7501:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7502:     }
                   7503:     if ($gotlock eq 'ok') {
                   7504:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7505:         my ($tmp)=keys(%curr_permissions);
                   7506:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7507:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7508:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7509:             if (ref($curr_controls) eq 'HASH') {
                   7510:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7511:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7512:                     if (defined($todelete{$itemnum})) {
                   7513:                         push(@deletions,$file_name."\0".$control_item);
                   7514:                     } else {
                   7515:                         if (defined($changed_items{$itemnum})) {
                   7516:                             $new_control{$changed_items{$itemnum}} = $now;
                   7517:                             push(@deletions,$file_name."\0".$control_item);
                   7518:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7519:                         } else {
                   7520:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7521:                         }
                   7522:                     }
1.745     raeburn  7523:                 }
                   7524:             }
                   7525:         }
1.970     raeburn  7526:         my ($group);
                   7527:         if (&is_course($domain,$user)) {
                   7528:             ($group,my $file) = split(/\//,$file_name,2);
                   7529:         }
1.749     raeburn  7530:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7531:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7532:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7533:         #  remove lock
                   7534:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7535:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7536:         my $sqlresult =
1.970     raeburn  7537:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7538:                                     $group);
1.749     raeburn  7539:     } else {
                   7540:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7541:     }
1.749     raeburn  7542:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7543: }
                   7544: 
1.827     raeburn  7545: sub make_public_indefinitely {
                   7546:     my ($requrl) = @_;
                   7547:     my $now = time;
                   7548:     my $action = 'activate';
                   7549:     my $aclnum = 0;
                   7550:     if (&is_portfolio_url($requrl)) {
                   7551:         my (undef,$udom,$unum,$file_name,$group) =
                   7552:             &parse_portfolio_url($requrl);
                   7553:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7554:         my %access_controls = &get_access_controls($current_perms,
                   7555:                                                    $group,$file_name);
                   7556:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7557:             my ($num,$scope,$end,$start) = 
                   7558:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7559:             if ($scope eq 'public') {
                   7560:                 if ($start <= $now && $end == 0) {
                   7561:                     $action = 'none';
                   7562:                 } else {
                   7563:                     $action = 'update';
                   7564:                     $aclnum = $num;
                   7565:                 }
                   7566:                 last;
                   7567:             }
                   7568:         }
                   7569:         if ($action eq 'none') {
                   7570:              return 'ok';
                   7571:         } else {
                   7572:             my %changes;
                   7573:             my $newend = 0;
                   7574:             my $newstart = $now;
                   7575:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7576:             $changes{$action}{$newkey} = {
                   7577:                 type => 'public',
                   7578:                 time => {
                   7579:                     start => $newstart,
                   7580:                     end   => $newend,
                   7581:                 },
                   7582:             };
                   7583:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7584:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7585:             return $outcome;
                   7586:         }
                   7587:     } else {
                   7588:         return 'invalid';
                   7589:     }
                   7590: }
                   7591: 
1.745     raeburn  7592: #------------------------------------------------------Get Marked as Read Only
                   7593: 
                   7594: sub get_marked_as_readonly {
                   7595:     my ($domain,$user,$what,$group) = @_;
                   7596:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7597:     my @readonly_files;
1.629     banghart 7598:     my $cmp1=$what;
                   7599:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7600:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7601:         if (defined($group)) {
                   7602:             if ($file_name !~ m-^\Q$group\E/-) {
                   7603:                 next;
                   7604:             }
                   7605:         }
1.561     banghart 7606:         if (ref($value) eq "ARRAY"){
                   7607:             foreach my $stored_what (@{$value}) {
1.629     banghart 7608:                 my $cmp2=$stored_what;
1.759     albertel 7609:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7610:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7611:                 }
1.629     banghart 7612:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7613:                     push(@readonly_files, $file_name);
1.745     raeburn  7614:                     last;
1.563     banghart 7615:                 } elsif (!defined($what)) {
                   7616:                     push(@readonly_files, $file_name);
1.745     raeburn  7617:                     last;
1.561     banghart 7618:                 }
                   7619:             }
1.745     raeburn  7620:         }
1.561     banghart 7621:     }
                   7622:     return @readonly_files;
                   7623: }
1.577     banghart 7624: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7625: 
1.577     banghart 7626: sub get_marked_as_readonly_hash {
1.745     raeburn  7627:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7628:     my %readonly_files;
1.745     raeburn  7629:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7630:         if (defined($group)) {
                   7631:             if ($file_name !~ m-^\Q$group\E/-) {
                   7632:                 next;
                   7633:             }
                   7634:         }
1.577     banghart 7635:         if (ref($value) eq "ARRAY"){
                   7636:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7637:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7638:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7639:                         if ($lock_descriptor eq 'graded') {
                   7640:                             $readonly_files{$file_name} = 'graded';
                   7641:                         } elsif ($lock_descriptor eq 'handback') {
                   7642:                             $readonly_files{$file_name} = 'handback';
                   7643:                         } else {
                   7644:                             if (!exists($readonly_files{$file_name})) {
                   7645:                                 $readonly_files{$file_name} = 'locked';
                   7646:                             }
                   7647:                         }
1.745     raeburn  7648:                     }
1.750     banghart 7649:                 } 
1.577     banghart 7650:             }
                   7651:         } 
                   7652:     }
                   7653:     return %readonly_files;
                   7654: }
1.559     banghart 7655: # ------------------------------------------------------------ Unmark as Read Only
                   7656: 
                   7657: sub unmark_as_readonly {
1.629     banghart 7658:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7659:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7660:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7661:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7662:     my $symb_crs = $what;
                   7663:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7664:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7665:     my ($tmp)=keys(%current_permissions);
                   7666:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7667:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7668:     foreach my $file (@readonly_files) {
1.759     albertel 7669: 	my $clean_file = &declutter_portfile($file);
                   7670: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7671: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7672:         my @new_locks;
                   7673:         my @del_keys;
                   7674:         if (ref($current_locks) eq "ARRAY"){
                   7675:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7676:                 my $compare=$locker;
1.749     raeburn  7677:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7678:                     $compare=join('',@{$locker});
1.746     raeburn  7679:                     if ($compare ne $symb_crs) {
                   7680:                         push(@new_locks, $locker);
                   7681:                     }
1.563     banghart 7682:                 }
                   7683:             }
1.650     albertel 7684:             if (scalar(@new_locks) > 0) {
1.563     banghart 7685:                 $current_permissions{$file} = \@new_locks;
                   7686:             } else {
                   7687:                 push(@del_keys, $file);
1.613     albertel 7688:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7689:                 delete($current_permissions{$file});
1.563     banghart 7690:             }
                   7691:         }
1.561     banghart 7692:     }
1.613     albertel 7693:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7694:     return;
                   7695: }
1.512     banghart 7696: 
1.17      www      7697: # ------------------------------------------------------------ Directory lister
                   7698: 
                   7699: sub dirlist {
1.955     raeburn  7700:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7701:     $uri=~s/^\///;
                   7702:     $uri=~s/\/$//;
1.253     stredwic 7703:     my ($udom, $uname);
1.955     raeburn  7704:     if ($getuserdir) {
1.253     stredwic 7705:         $udom = $userdomain;
                   7706:         $uname = $username;
1.955     raeburn  7707:     } else {
                   7708:         (undef,$udom,$uname)=split(/\//,$uri);
                   7709:         if(defined($userdomain)) {
                   7710:             $udom = $userdomain;
                   7711:         }
                   7712:         if(defined($username)) {
                   7713:             $uname = $username;
                   7714:         }
1.253     stredwic 7715:     }
1.955     raeburn  7716:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7717: 
1.955     raeburn  7718:     $dirRoot = $perlvar{'lonDocRoot'};
                   7719:     if (defined($getpropath)) {
                   7720:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7721:         $dirRoot =~ s/\/$//;
1.955     raeburn  7722:     } elsif (defined($getuserdir)) {
                   7723:         my $subdir=$uname.'__';
                   7724:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7725:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7726:                    ."/$udom/$subdir/$uname";
                   7727:     } elsif (defined($alternateRoot)) {
                   7728:         $dirRoot = $alternateRoot;
1.751     banghart 7729:     }
1.253     stredwic 7730: 
                   7731:     if($udom) {
                   7732:         if($uname) {
1.955     raeburn  7733:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7734:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7735:                               .':'.&escape($uname).':'.&escape($udom),
                   7736:                               &homeserver($uname,$udom));
                   7737:             if ($listing eq 'unknown_cmd') {
                   7738:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7739:                                   &homeserver($uname,$udom));
                   7740:             } else {
                   7741:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7742:             }
1.605     matthew  7743:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7744:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7745: 				  &homeserver($uname,$udom));
1.605     matthew  7746:                 @listing_results = split(/:/,$listing);
                   7747:             } else {
                   7748:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7749:             }
                   7750:             return @listing_results;
1.955     raeburn  7751:         } elsif(!$alternateRoot) {
1.800     albertel 7752:             my %allusers;
1.841     albertel 7753: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7754:  	    foreach my $tryserver (keys(%servers)) {
                   7755:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7756:                                   &escape($udom),$tryserver);
                   7757:                 if ($listing eq 'unknown_cmd') {
                   7758: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7759: 				      $udom, $tryserver);
                   7760:                 } else {
                   7761:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7762:                 }
1.841     albertel 7763: 		if ($listing eq 'unknown_cmd') {
                   7764: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7765: 				      $udom, $tryserver);
                   7766: 		    @listing_results = split(/:/,$listing);
                   7767: 		} else {
                   7768: 		    @listing_results =
                   7769: 			map { &unescape($_); } split(/:/,$listing);
                   7770: 		}
                   7771: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7772: 		    $listing_results[0] ne 'empty'       &&
                   7773: 		    $listing_results[0] ne 'con_lost') {
                   7774: 		    foreach my $line (@listing_results) {
                   7775: 			my ($entry) = split(/&/,$line,2);
                   7776: 			$allusers{$entry} = 1;
                   7777: 		    }
                   7778: 		}
1.253     stredwic 7779:             }
                   7780:             my $alluserstr='';
1.800     albertel 7781:             foreach my $user (sort(keys(%allusers))) {
                   7782:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7783:             }
                   7784:             $alluserstr=~s/:$//;
                   7785:             return split(/:/,$alluserstr);
                   7786:         } else {
1.800     albertel 7787:             return ('missing user name');
1.253     stredwic 7788:         }
1.955     raeburn  7789:     } elsif(!defined($getpropath)) {
1.841     albertel 7790:         my @all_domains = sort(&all_domains());
1.955     raeburn  7791:         foreach my $domain (@all_domains) {
                   7792:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7793:         }
                   7794:         return @all_domains;
                   7795:     } else {
1.800     albertel 7796:         return ('missing domain');
1.275     stredwic 7797:     }
                   7798: }
                   7799: 
                   7800: # --------------------------------------------- GetFileTimestamp
                   7801: # This function utilizes dirlist and returns the date stamp for
                   7802: # when it was last modified.  It will also return an error of -1
                   7803: # if an error occurs
                   7804: 
                   7805: sub GetFileTimestamp {
1.955     raeburn  7806:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7807:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7808:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7809:     my ($fileStat) = 
                   7810:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7811:                                  undef,$getuserdir);
1.275     stredwic 7812:     my @stats = split('&', $fileStat);
                   7813:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7814:         # @stats contains first the filename, then the stat output
                   7815:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7816:     } else {
                   7817:         return -1;
1.253     stredwic 7818:     }
1.26      www      7819: }
                   7820: 
1.712     albertel 7821: sub stat_file {
                   7822:     my ($uri) = @_;
1.787     albertel 7823:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7824: 
1.955     raeburn  7825:     my ($udom,$uname,$file);
1.712     albertel 7826:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7827: 	($udom,$uname,$file) =
1.811     albertel 7828: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7829: 	$file = 'userfiles/'.$file;
                   7830:     }
                   7831:     if ($uri =~ m-^/res/-) {
                   7832: 	($udom,$uname) = 
1.807     albertel 7833: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7834: 	$file = $uri;
                   7835:     }
                   7836: 
                   7837:     if (!$udom || !$uname || !$file) {
                   7838: 	# unable to handle the uri
                   7839: 	return ();
                   7840:     }
1.956     raeburn  7841:     my $getpropath;
                   7842:     if ($file =~ /^userfiles\//) {
                   7843:         $getpropath = 1;
                   7844:     }
1.955     raeburn  7845:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7846:     my @stats = split('&', $result);
1.721     banghart 7847:     
1.712     albertel 7848:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7849: 	shift(@stats); #filename is first
                   7850: 	return @stats;
                   7851:     }
                   7852:     return ();
                   7853: }
                   7854: 
1.26      www      7855: # -------------------------------------------------------- Value of a Condition
                   7856: 
1.713     albertel 7857: # gets the value of a specific preevaluated condition
                   7858: #    stored in the string  $env{user.state.<cid>}
                   7859: # or looks up a condition reference in the bighash and if if hasn't
                   7860: # already been evaluated recurses into docondval to get the value of
                   7861: # the condition, then memoizing it to 
                   7862: #   $env{user.state.<cid>.<condition>}
1.40      www      7863: sub directcondval {
                   7864:     my $number=shift;
1.620     albertel 7865:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7866: 	&Apache::lonuserstate::evalstate();
                   7867:     }
1.713     albertel 7868:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7869: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7870:     } elsif ($number =~ /^_/) {
                   7871: 	my $sub_condition;
                   7872: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7873: 		&GDBM_READER(),0640)) {
                   7874: 	    $sub_condition=$bighash{'conditions'.$number};
                   7875: 	    untie(%bighash);
                   7876: 	}
                   7877: 	my $value = &docondval($sub_condition);
1.949     raeburn  7878: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7879: 	return $value;
                   7880:     }
1.620     albertel 7881:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7882:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7883:     } else {
                   7884:        return 2;
                   7885:     }
                   7886: }
                   7887: 
1.713     albertel 7888: # get the collection of conditions for this resource
1.26      www      7889: sub condval {
                   7890:     my $condidx=shift;
1.54      www      7891:     my $allpathcond='';
1.713     albertel 7892:     foreach my $cond (split(/\|/,$condidx)) {
                   7893: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7894: 	    $allpathcond.=
                   7895: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7896: 	}
1.191     harris41 7897:     }
1.54      www      7898:     $allpathcond=~s/\|$//;
1.713     albertel 7899:     return &docondval($allpathcond);
                   7900: }
                   7901: 
                   7902: #evaluates an expression of conditions
                   7903: sub docondval {
                   7904:     my ($allpathcond) = @_;
                   7905:     my $result=0;
                   7906:     if ($env{'request.course.id'}
                   7907: 	&& defined($allpathcond)) {
                   7908: 	my $operand='|';
                   7909: 	my @stack;
                   7910: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7911: 	    if ($chunk eq '(') {
                   7912: 		push @stack,($operand,$result);
                   7913: 	    } elsif ($chunk eq ')') {
                   7914: 		my $before=pop @stack;
                   7915: 		if (pop @stack eq '&') {
                   7916: 		    $result=$result>$before?$before:$result;
                   7917: 		} else {
                   7918: 		    $result=$result>$before?$result:$before;
                   7919: 		}
                   7920: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7921: 		$operand=$chunk;
                   7922: 	    } else {
                   7923: 		my $new=directcondval($chunk);
                   7924: 		if ($operand eq '&') {
                   7925: 		    $result=$result>$new?$new:$result;
                   7926: 		} else {
                   7927: 		    $result=$result>$new?$result:$new;
                   7928: 		}
                   7929: 	    }
                   7930: 	}
1.26      www      7931:     }
                   7932:     return $result;
1.421     albertel 7933: }
                   7934: 
                   7935: # ---------------------------------------------------- Devalidate courseresdata
                   7936: 
                   7937: sub devalidatecourseresdata {
                   7938:     my ($coursenum,$coursedomain)=@_;
                   7939:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7940:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7941: }
                   7942: 
1.763     www      7943: 
1.200     www      7944: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7945: #
                   7946: #  Parameters:
                   7947: #      $coursenum    - Number of the course.
                   7948: #      $coursedomain - Domain at which the course was created.
                   7949: #  Returns:
                   7950: #     A hash of the course parameters along (I think) with timestamps
                   7951: #     and version info.
1.877     foxr     7952: 
1.624     albertel 7953: sub get_courseresdata {
                   7954:     my ($coursenum,$coursedomain)=@_;
1.200     www      7955:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7956:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7957:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7958:     my %dumpreply;
1.417     albertel 7959:     unless (defined($cached)) {
1.624     albertel 7960: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7961: 	$result=\%dumpreply;
1.251     albertel 7962: 	my ($tmp) = keys(%dumpreply);
                   7963: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7964: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7965: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7966: 	    return $tmp;
1.416     albertel 7967: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7968: 	    $result=undef;
1.599     albertel 7969: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7970: 	}
                   7971:     }
1.624     albertel 7972:     return $result;
                   7973: }
                   7974: 
1.633     albertel 7975: sub devalidateuserresdata {
                   7976:     my ($uname,$udom)=@_;
                   7977:     my $hashid="$udom:$uname";
                   7978:     &devalidate_cache_new('userres',$hashid);
                   7979: }
                   7980: 
1.624     albertel 7981: sub get_userresdata {
                   7982:     my ($uname,$udom)=@_;
                   7983:     #most student don\'t have any data set, check if there is some data
                   7984:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7985: 
                   7986:     my $hashid="$udom:$uname";
                   7987:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7988:     if (!defined($cached)) {
                   7989: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7990: 	$result=\%resourcedata;
                   7991: 	&do_cache_new('userres',$hashid,$result,600);
                   7992:     }
                   7993:     my ($tmp)=keys(%$result);
                   7994:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7995: 	return $result;
                   7996:     }
                   7997:     #error 2 occurs when the .db doesn't exist
                   7998:     if ($tmp!~/error: 2 /) {
1.672     albertel 7999: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8000: 		 " Trying to get resource data for ".
                   8001: 		 $uname." at ".$udom.": ".
                   8002: 		 $tmp."</font>");
                   8003:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8004: 	#&EXT_cache_set($udom,$uname);
                   8005: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8006: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8007:     }
                   8008:     return $tmp;
                   8009: }
1.879     foxr     8010: #----------------------------------------------- resdata - return resource data
                   8011: #  Purpose:
                   8012: #    Return resource data for either users or for a course.
                   8013: #  Parameters:
                   8014: #     $name      - Course/user name.
                   8015: #     $domain    - Name of the domain the user/course is registered on.
                   8016: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8017: #     @which     - Array of names of resources desired.
                   8018: #  Returns:
                   8019: #     The value of the first reasource in @which that is found in the
                   8020: #     resource hash.
                   8021: #  Exceptional Conditions:
                   8022: #     If the $type passed in is not valid (not the string 'course' or 
                   8023: #     'user', an undefined  reference is returned.
                   8024: #     If none of the resources are found, an undef is returned
1.624     albertel 8025: sub resdata {
                   8026:     my ($name,$domain,$type,@which)=@_;
                   8027:     my $result;
                   8028:     if ($type eq 'course') {
                   8029: 	$result=&get_courseresdata($name,$domain);
                   8030:     } elsif ($type eq 'user') {
                   8031: 	$result=&get_userresdata($name,$domain);
                   8032:     }
                   8033:     if (!ref($result)) { return $result; }    
1.251     albertel 8034:     foreach my $item (@which) {
1.927     albertel 8035: 	if (defined($result->{$item->[0]})) {
                   8036: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8037: 	}
1.250     albertel 8038:     }
1.291     albertel 8039:     return undef;
1.200     www      8040: }
                   8041: 
1.379     matthew  8042: #
                   8043: # EXT resource caching routines
                   8044: #
                   8045: 
                   8046: sub clear_EXT_cache_status {
1.383     albertel 8047:     &delenv('cache.EXT.');
1.379     matthew  8048: }
                   8049: 
                   8050: sub EXT_cache_status {
                   8051:     my ($target_domain,$target_user) = @_;
1.383     albertel 8052:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8053:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8054:         # We know already the user has no data
                   8055:         return 1;
                   8056:     } else {
                   8057:         return 0;
                   8058:     }
                   8059: }
                   8060: 
                   8061: sub EXT_cache_set {
                   8062:     my ($target_domain,$target_user) = @_;
1.383     albertel 8063:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8064:     #&appenv({$cachename => time});
1.379     matthew  8065: }
                   8066: 
1.28      www      8067: # --------------------------------------------------------- Value of a Variable
1.58      www      8068: sub EXT {
1.715     albertel 8069: 
1.395     albertel 8070:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8071:     unless ($varname) { return ''; }
1.218     albertel 8072:     #get real user name/domain, courseid and symb
                   8073:     my $courseid;
1.359     albertel 8074:     my $publicuser;
1.427     www      8075:     if ($symbparm) {
                   8076: 	$symbparm=&get_symb_from_alias($symbparm);
                   8077:     }
1.218     albertel 8078:     if (!($uname && $udom)) {
1.790     albertel 8079:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8080:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8081:     } else {
1.620     albertel 8082: 	$courseid=$env{'request.course.id'};
1.218     albertel 8083:     }
1.48      www      8084:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8085:     my $rest;
1.320     albertel 8086:     if (defined($therest[0])) {
1.48      www      8087:        $rest=join('.',@therest);
                   8088:     } else {
                   8089:        $rest='';
                   8090:     }
1.320     albertel 8091: 
1.57      www      8092:     my $qualifierrest=$qualifier;
                   8093:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8094:     my $spacequalifierrest=$space;
                   8095:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8096:     if ($realm eq 'user') {
1.48      www      8097: # --------------------------------------------------------------- user.resource
                   8098: 	if ($space eq 'resource') {
1.651     albertel 8099: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8100: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8101: 		 &&
1.744     albertel 8102: 		 ($symbparm eq &symbread()) ) {	
                   8103: 		# if we are in the middle of processing the resource the
                   8104: 		# get the value we are planning on committing
                   8105:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8106:                     return $Apache::lonhomework::results{$qualifierrest};
                   8107:                 } else {
                   8108:                     return $Apache::lonhomework::history{$qualifierrest};
                   8109:                 }
1.335     albertel 8110: 	    } else {
1.359     albertel 8111: 		my %restored;
1.620     albertel 8112: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8113: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8114: 		} else {
                   8115: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8116: 		}
1.335     albertel 8117: 		return $restored{$qualifierrest};
                   8118: 	    }
1.48      www      8119: # ----------------------------------------------------------------- user.access
                   8120:         } elsif ($space eq 'access') {
1.218     albertel 8121: 	    # FIXME - not supporting calls for a specific user
1.48      www      8122:             return &allowed($qualifier,$rest);
                   8123: # ------------------------------------------ user.preferences, user.environment
                   8124:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8125: 	    if (($uname eq $env{'user.name'}) &&
                   8126: 		($udom eq $env{'user.domain'})) {
                   8127: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8128: 	    } else {
1.359     albertel 8129: 		my %returnhash;
                   8130: 		if (!$publicuser) {
                   8131: 		    %returnhash=&userenvironment($udom,$uname,
                   8132: 						 $qualifierrest);
                   8133: 		}
1.218     albertel 8134: 		return $returnhash{$qualifierrest};
                   8135: 	    }
1.48      www      8136: # ----------------------------------------------------------------- user.course
                   8137:         } elsif ($space eq 'course') {
1.218     albertel 8138: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8139:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8140: # ------------------------------------------------------------------- user.role
                   8141:         } elsif ($space eq 'role') {
1.218     albertel 8142: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8143:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8144:             if ($qualifier eq 'value') {
                   8145: 		return $role;
                   8146:             } elsif ($qualifier eq 'extent') {
                   8147:                 return $where;
                   8148:             }
                   8149: # ----------------------------------------------------------------- user.domain
                   8150:         } elsif ($space eq 'domain') {
1.218     albertel 8151:             return $udom;
1.48      www      8152: # ------------------------------------------------------------------- user.name
                   8153:         } elsif ($space eq 'name') {
1.218     albertel 8154:             return $uname;
1.48      www      8155: # ---------------------------------------------------- Any other user namespace
1.29      www      8156:         } else {
1.359     albertel 8157: 	    my %reply;
                   8158: 	    if (!$publicuser) {
                   8159: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8160: 	    }
                   8161: 	    return $reply{$qualifierrest};
1.48      www      8162:         }
1.236     www      8163:     } elsif ($realm eq 'query') {
                   8164: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8165:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8166: 						[$spacequalifierrest]);
1.620     albertel 8167: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8168:    } elsif ($realm eq 'request') {
1.48      www      8169: # ------------------------------------------------------------- request.browser
                   8170:         if ($space eq 'browser') {
1.430     www      8171: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8172: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8173: 		    return 1;
                   8174: 		} else {
                   8175: 		    return 0;
                   8176: 		}
                   8177: 	    } else {
1.620     albertel 8178: 		return $env{'browser.'.$qualifier};
1.430     www      8179: 	    }
1.57      www      8180: # ------------------------------------------------------------ request.filename
                   8181:         } else {
1.620     albertel 8182:             return $env{'request.'.$spacequalifierrest};
1.29      www      8183:         }
1.28      www      8184:     } elsif ($realm eq 'course') {
1.48      www      8185: # ---------------------------------------------------------- course.description
1.620     albertel 8186:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8187:     } elsif ($realm eq 'resource') {
1.165     www      8188: 
1.620     albertel 8189: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8190: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8191: 	}
1.693     albertel 8192: 
                   8193: 	if ($space eq 'title') {
                   8194: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8195: 	    return &gettitle($symbparm);
                   8196: 	}
                   8197: 	
                   8198: 	if ($space eq 'map') {
                   8199: 	    my ($map) = &decode_symb($symbparm);
                   8200: 	    return &symbread($map);
                   8201: 	}
1.905     albertel 8202: 	if ($space eq 'filename') {
                   8203: 	    if ($symbparm) {
                   8204: 		return &clutter((&decode_symb($symbparm))[2]);
                   8205: 	    }
                   8206: 	    return &hreflocation('',$env{'request.filename'});
                   8207: 	}
1.693     albertel 8208: 
                   8209: 	my ($section, $group, @groups);
1.593     albertel 8210: 	my ($courselevelm,$courselevel);
1.539     albertel 8211: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8212: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8213: 
1.218     albertel 8214: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8215: 
1.60      www      8216: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8217: 	    my $symbp=$symbparm;
1.735     albertel 8218: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8219: 
                   8220: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8221: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8222: 
1.620     albertel 8223: 	    if (($env{'user.name'} eq $uname) &&
                   8224: 		($env{'user.domain'} eq $udom)) {
                   8225: 		$section=$env{'request.course.sec'};
1.733     raeburn  8226:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8227:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8228: 	    } else {
1.539     albertel 8229: 		if (! defined($usection)) {
1.551     albertel 8230: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8231: 		} else {
                   8232: 		    $section = $usection;
                   8233: 		}
1.733     raeburn  8234:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8235: 	    }
                   8236: 
                   8237: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8238: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8239: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8240: 
1.593     albertel 8241: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8242: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8243: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8244: 
1.60      www      8245: # ----------------------------------------------------------- first, check user
1.624     albertel 8246: 
                   8247: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8248: 				       ([$courselevelr,'resource'],
                   8249: 					[$courselevelm,'map'     ],
                   8250: 					[$courselevel, 'course'  ]));
1.931     albertel 8251: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8252: 
1.594     albertel 8253: # ------------------------------------------------ second, check some of course
1.684     raeburn  8254:             my $coursereply;
1.691     raeburn  8255:             if (@groups > 0) {
                   8256:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8257:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8258:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8259:             }
1.96      www      8260: 
1.684     raeburn  8261: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8262: 				  $env{'course.'.$courseid.'.domain'},
                   8263: 				  'course',
                   8264: 				  ([$seclevelr,   'resource'],
                   8265: 				   [$seclevelm,   'map'     ],
                   8266: 				   [$seclevel,    'course'  ],
                   8267: 				   [$courselevelr,'resource']));
                   8268: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8269: 
1.60      www      8270: # ------------------------------------------------------ third, check map parms
1.218     albertel 8271: 	    my %parmhash=();
                   8272: 	    my $thisparm='';
                   8273: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8274: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8275: 		    &GDBM_READER(),0640)) {
1.218     albertel 8276: 		$thisparm=$parmhash{$symbparm};
                   8277: 		untie(%parmhash);
                   8278: 	    }
1.927     albertel 8279: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8280: 	}
1.594     albertel 8281: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8282: 
1.218     albertel 8283: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8284: 	my $filename;
                   8285: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8286: 	if ($symbparm) {
1.409     www      8287: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8288: 	} else {
1.620     albertel 8289: 	    $filename=$env{'request.filename'};
1.282     albertel 8290: 	}
                   8291: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8292: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8293: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8294: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8295: 
1.927     albertel 8296: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8297: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8298: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8299: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8300: 				     $env{'course.'.$courseid.'.domain'},
                   8301: 				     'course',
1.927     albertel 8302: 				     ([$courselevelm,'map'   ],
                   8303: 				      [$courselevel, 'course']));
                   8304: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8305: 	}
1.145     www      8306: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8307: 	unless ($space eq '0') {
1.336     albertel 8308: 	    my @parts=split(/_/,$space);
                   8309: 	    my $id=pop(@parts);
                   8310: 	    my $part=join('_',@parts);
                   8311: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8312: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8313: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8314: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8315: 	}
1.395     albertel 8316: 	if ($recurse) { return undef; }
                   8317: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8318: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8319: # ---------------------------------------------------- Any other user namespace
                   8320:     } elsif ($realm eq 'environment') {
                   8321: # ----------------------------------------------------------------- environment
1.620     albertel 8322: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8323: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8324: 	} else {
1.770     albertel 8325: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8326: 		return '';
                   8327: 	    }
1.219     albertel 8328: 	    my %returnhash=&userenvironment($udom,$uname,
                   8329: 					    $spacequalifierrest);
                   8330: 	    return $returnhash{$spacequalifierrest};
                   8331: 	}
1.28      www      8332:     } elsif ($realm eq 'system') {
1.48      www      8333: # ----------------------------------------------------------------- system.time
                   8334: 	if ($space eq 'time') {
                   8335: 	    return time;
                   8336:         }
1.696     albertel 8337:     } elsif ($realm eq 'server') {
                   8338: # ----------------------------------------------------------------- system.time
                   8339: 	if ($space eq 'name') {
                   8340: 	    return $ENV{'SERVER_NAME'};
                   8341:         }
1.28      www      8342:     }
1.48      www      8343:     return '';
1.61      www      8344: }
                   8345: 
1.927     albertel 8346: sub get_reply {
                   8347:     my ($reply_value) = @_;
1.940     raeburn  8348:     if (ref($reply_value) eq 'ARRAY') {
                   8349:         if (wantarray) {
                   8350: 	    return @$reply_value;
                   8351:         }
                   8352:         return $reply_value->[0];
                   8353:     } else {
                   8354:         return $reply_value;
1.927     albertel 8355:     }
                   8356: }
                   8357: 
1.691     raeburn  8358: sub check_group_parms {
                   8359:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8360:     my @groupitems = ();
                   8361:     my $resultitem;
1.927     albertel 8362:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8363:     foreach my $group (@{$groups}) {
                   8364:         foreach my $level (@levels) {
1.927     albertel 8365:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8366:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8367:         }
                   8368:     }
                   8369:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8370:                             $env{'course.'.$courseid.'.domain'},
                   8371:                                      'course',@groupitems);
                   8372:     return $coursereply;
                   8373: }
                   8374: 
                   8375: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8376:     my ($courseid,@groups) = @_;
                   8377:     @groups = sort(@groups);
1.691     raeburn  8378:     return @groups;
                   8379: }
                   8380: 
1.395     albertel 8381: sub packages_tab_default {
                   8382:     my ($uri,$varname)=@_;
                   8383:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8384: 
                   8385:     my (@extension,@specifics,$do_default);
                   8386:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8387: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8388: 	if ($pack_type eq 'default') {
                   8389: 	    $do_default=1;
                   8390: 	} elsif ($pack_type eq 'extension') {
                   8391: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8392: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8393: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8394: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8395: 	}
                   8396:     }
                   8397:     # first look for a package that matches the requested part id
                   8398:     foreach my $package (@specifics) {
                   8399: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8400: 	next if ($pack_part ne $part);
                   8401: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8402: 	    return $packagetab{"$pack_type&$name&default"};
                   8403: 	}
                   8404:     }
                   8405:     # look for any possible matching non extension_ package
                   8406:     foreach my $package (@specifics) {
                   8407: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8408: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8409: 	    return $packagetab{"$pack_type&$name&default"};
                   8410: 	}
1.585     albertel 8411: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8412: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8413: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8414: 	}
                   8415:     }
1.738     albertel 8416:     # look for any posible extension_ match
                   8417:     foreach my $package (@extension) {
                   8418: 	my ($package,$pack_type)=@{$package};
                   8419: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8420: 	    return $packagetab{"$pack_type&$name&default"};
                   8421: 	}
                   8422: 	if (defined($packagetab{$package."&$name&default"})) {
                   8423: 	    return $packagetab{$package."&$name&default"};
                   8424: 	}
                   8425:     }
                   8426:     # look for a global default setting
                   8427:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8428: 	return $packagetab{"default&$name&default"};
                   8429:     }
1.395     albertel 8430:     return undef;
                   8431: }
                   8432: 
1.334     albertel 8433: sub add_prefix_and_part {
                   8434:     my ($prefix,$part)=@_;
                   8435:     my $keyroot;
                   8436:     if (defined($prefix) && $prefix !~ /^__/) {
                   8437: 	# prefix that has a part already
                   8438: 	$keyroot=$prefix;
                   8439:     } elsif (defined($prefix)) {
                   8440: 	# prefix that is missing a part
                   8441: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8442:     } else {
                   8443: 	# no prefix at all
                   8444: 	if (defined($part)) { $keyroot='_'.$part; }
                   8445:     }
                   8446:     return $keyroot;
                   8447: }
                   8448: 
1.71      www      8449: # ---------------------------------------------------------------- Get metadata
                   8450: 
1.599     albertel 8451: my %metaentry;
1.71      www      8452: sub metadata {
1.176     www      8453:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8454:     $uri=&declutter($uri);
1.288     albertel 8455:     # if it is a non metadata possible uri return quickly
1.529     albertel 8456:     if (($uri eq '') || 
                   8457: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8458: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8459:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8460: 	return undef;
                   8461:     }
                   8462:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8463: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8464: 	return undef;
1.288     albertel 8465:     }
1.73      www      8466:     my $filename=$uri;
                   8467:     $uri=~s/\.meta$//;
1.172     www      8468: #
                   8469: # Is the metadata already cached?
1.177     www      8470: # Look at timestamp of caching
1.172     www      8471: # Everything is cached by the main uri, libraries are never directly cached
                   8472: #
1.428     albertel 8473:     if (!defined($liburi)) {
1.599     albertel 8474: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8475: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8476:     }
                   8477:     {
1.172     www      8478: #
                   8479: # Is this a recursive call for a library?
                   8480: #
1.599     albertel 8481: #	if (! exists($metacache{$uri})) {
                   8482: #	    $metacache{$uri}={};
                   8483: #	}
1.924     albertel 8484: 	my $cachetime = 60*60;
1.171     www      8485:         if ($liburi) {
                   8486: 	    $liburi=&declutter($liburi);
                   8487:             $filename=$liburi;
1.401     bowersj2 8488:         } else {
1.599     albertel 8489: 	    &devalidate_cache_new('meta',$uri);
                   8490: 	    undef(%metaentry);
1.401     bowersj2 8491: 	}
1.140     www      8492:         my %metathesekeys=();
1.73      www      8493:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8494: 	my $metastring;
1.924     albertel 8495: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8496: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8497: 	    $metastring = 
1.929     albertel 8498: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8499: 					  ('grade_target' => 'meta'));
                   8500: 	    $cachetime = 1; # only want this cached in the child not long term
                   8501: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8502: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8503: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8504: 	    $metastring=&getfile($file);
1.489     albertel 8505: 	}
1.208     albertel 8506:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8507:         my $token;
1.140     www      8508:         undef %metathesekeys;
1.71      www      8509:         while ($token=$parser->get_token) {
1.339     albertel 8510: 	    if ($token->[0] eq 'S') {
                   8511: 		if (defined($token->[2]->{'package'})) {
1.172     www      8512: #
                   8513: # This is a package - get package info
                   8514: #
1.339     albertel 8515: 		    my $package=$token->[2]->{'package'};
                   8516: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8517: 		    if (defined($token->[2]->{'id'})) { 
                   8518: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8519: 		    }
1.599     albertel 8520: 		    if ($metaentry{':packages'}) {
                   8521: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8522: 		    } else {
1.599     albertel 8523: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8524: 		    }
1.736     albertel 8525: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8526: 			my $part=$keyroot;
                   8527: 			$part=~s/^\_//;
1.736     albertel 8528: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8529: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8530: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8531: 			    # ignore package.tab specified default values
                   8532:                             # here &package_tab_default() will fetch those
                   8533: 			    if ($subp eq 'default') { next; }
1.736     albertel 8534: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8535: 			    my $unikey;
                   8536: 			    if ($pack =~ /_0$/) {
                   8537: 				$unikey='parameter_0_'.$name;
                   8538: 				$part=0;
                   8539: 			    } else {
                   8540: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8541: 			    }
1.339     albertel 8542: 			    if ($subp eq 'display') {
                   8543: 				$value.=' [Part: '.$part.']';
                   8544: 			    }
1.599     albertel 8545: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8546: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8547: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8548: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8549: 			    }
1.599     albertel 8550: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8551: 				$metaentry{':'.$unikey}=
                   8552: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8553: 			    }
1.339     albertel 8554: 			}
                   8555: 		    }
                   8556: 		} else {
1.172     www      8557: #
                   8558: # This is not a package - some other kind of start tag
1.339     albertel 8559: #
                   8560: 		    my $entry=$token->[1];
                   8561: 		    my $unikey;
                   8562: 		    if ($entry eq 'import') {
                   8563: 			$unikey='';
                   8564: 		    } else {
                   8565: 			$unikey=$entry;
                   8566: 		    }
                   8567: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8568: 
                   8569: 		    if (defined($token->[2]->{'id'})) { 
                   8570: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8571: 		    }
1.175     www      8572: 
1.339     albertel 8573: 		    if ($entry eq 'import') {
1.175     www      8574: #
                   8575: # Importing a library here
1.339     albertel 8576: #
                   8577: 			if ($depthcount<20) {
                   8578: 			    my $location=$parser->get_text('/import');
                   8579: 			    my $dir=$filename;
                   8580: 			    $dir=~s|[^/]*$||;
                   8581: 			    $location=&filelocation($dir,$location);
1.736     albertel 8582: 			    my $metadata = 
                   8583: 				&metadata($uri,'keys', $location,$unikey,
                   8584: 					  $depthcount+1);
                   8585: 			    foreach my $meta (split(',',$metadata)) {
                   8586: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8587: 				$metathesekeys{$meta}=1;
1.339     albertel 8588: 			    }
                   8589: 			}
                   8590: 		    } else { 
                   8591: 			if (defined($token->[2]->{'name'})) { 
                   8592: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8593: 			}
                   8594: 			$metathesekeys{$unikey}=1;
1.736     albertel 8595: 			foreach my $param (@{$token->[3]}) {
                   8596: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8597: 				$token->[2]->{$param};
1.339     albertel 8598: 			}
                   8599: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8600: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8601: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8602: 		 # only ws inside the tag, and not in default, so use default
                   8603: 		 # as value
1.599     albertel 8604: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8605: 			} elsif ( $internaltext =~ /\S/ ) {
                   8606: 		  # something interesting inside the tag
                   8607: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8608: 			} else {
1.908     albertel 8609: 		  # no interesting values, don't set a default
1.339     albertel 8610: 			}
1.172     www      8611: # end of not-a-package not-a-library import
1.339     albertel 8612: 		    }
1.172     www      8613: # end of not-a-package start tag
1.339     albertel 8614: 		}
1.172     www      8615: # the next is the end of "start tag"
1.339     albertel 8616: 	    }
                   8617: 	}
1.483     albertel 8618: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8619: 	$extension = lc($extension);
                   8620: 	if ($extension eq 'htm') { $extension='html'; }
                   8621: 
1.737     albertel 8622: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8623: 	    #no specific packages #how's our extension
                   8624: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8625: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8626: 					 \%metathesekeys);
                   8627: 	}
1.883     albertel 8628: 
                   8629: 	if (!exists($metaentry{':packages'})
                   8630: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8631: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8632: 		#no specific packages well let's get default then
                   8633: 		if ($key!~/^default&/) { next; }
1.488     albertel 8634: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8635: 					     \%metathesekeys);
                   8636: 	    }
                   8637: 	}
1.338     www      8638: # are there custom rights to evaluate
1.599     albertel 8639: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8640: 
1.338     www      8641:     #
                   8642:     # Importing a rights file here
1.339     albertel 8643:     #
                   8644: 	    unless ($depthcount) {
1.599     albertel 8645: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8646: 		my $dir=$filename;
                   8647: 		$dir=~s|[^/]*$||;
                   8648: 		$location=&filelocation($dir,$location);
1.736     albertel 8649: 		my $rights_metadata =
                   8650: 		    &metadata($uri,'keys',$location,'_rights',
                   8651: 			      $depthcount+1);
                   8652: 		foreach my $rights (split(',',$rights_metadata)) {
                   8653: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8654: 		    $metathesekeys{$rights}=1;
1.339     albertel 8655: 		}
                   8656: 	    }
                   8657: 	}
1.737     albertel 8658: 	# uniqifiy package listing
                   8659: 	my %seen;
                   8660: 	my @uniq_packages =
                   8661: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8662: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8663: 
                   8664: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8665: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8666: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8667: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8668: # this is the end of "was not already recently cached
1.71      www      8669:     }
1.599     albertel 8670:     return $metaentry{':'.$what};
1.261     albertel 8671: }
                   8672: 
1.488     albertel 8673: sub metadata_create_package_def {
1.483     albertel 8674:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8675:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8676:     if ($subp eq 'default') { next; }
                   8677:     
1.599     albertel 8678:     if (defined($metaentry{':packages'})) {
                   8679: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8680:     } else {
1.599     albertel 8681: 	$metaentry{':packages'}=$package;
1.483     albertel 8682:     }
                   8683:     my $value=$packagetab{$key};
                   8684:     my $unikey;
                   8685:     $unikey='parameter_0_'.$name;
1.599     albertel 8686:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8687:     $$metathesekeys{$unikey}=1;
1.599     albertel 8688:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8689: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8690:     }
1.599     albertel 8691:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8692: 	$metaentry{':'.$unikey}=
                   8693: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8694:     }
                   8695: }
                   8696: 
1.261     albertel 8697: sub metadata_generate_part0 {
                   8698:     my ($metadata,$metacache,$uri) = @_;
                   8699:     my %allnames;
1.737     albertel 8700:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8701: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8702: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8703: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8704: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8705: 	    $allnames{$name}=$part;
                   8706: 	  }
                   8707: 	}
                   8708:     }
                   8709:     foreach my $name (keys(%allnames)) {
                   8710:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8711:       my $key=":parameter_0_$name";
1.261     albertel 8712:       $$metacache{"$key.part"}='0';
                   8713:       $$metacache{"$key.name"}=$name;
1.428     albertel 8714:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8715: 					   $allnames{$name}.'_'.$name.
                   8716: 					   '.type'};
1.428     albertel 8717:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8718: 			     '.display'};
1.644     www      8719:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8720:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8721:       $$metacache{"$key.display"}=$olddis;
                   8722:     }
1.71      www      8723: }
                   8724: 
1.764     albertel 8725: # ------------------------------------------------------ Devalidate title cache
                   8726: 
                   8727: sub devalidate_title_cache {
                   8728:     my ($url)=@_;
                   8729:     if (!$env{'request.course.id'}) { return; }
                   8730:     my $symb=&symbread($url);
                   8731:     if (!$symb) { return; }
                   8732:     my $key=$env{'request.course.id'}."\0".$symb;
                   8733:     &devalidate_cache_new('title',$key);
                   8734: }
                   8735: 
1.1014    droeschl 8736: # ------------------------------------------------- Get the title of a course
                   8737: 
                   8738: sub current_course_title {
                   8739:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8740: }
1.301     www      8741: # ------------------------------------------------- Get the title of a resource
                   8742: 
                   8743: sub gettitle {
                   8744:     my $urlsymb=shift;
                   8745:     my $symb=&symbread($urlsymb);
1.534     albertel 8746:     if ($symb) {
1.620     albertel 8747: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8748: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8749: 	if (defined($cached)) { 
                   8750: 	    return $result;
                   8751: 	}
1.534     albertel 8752: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8753: 	my $title='';
1.907     albertel 8754: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8755: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8756: 	} else {
                   8757: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8758: 		    &GDBM_READER(),0640)) {
                   8759: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8760: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8761: 		untie(%bighash);
                   8762: 	    }
1.534     albertel 8763: 	}
                   8764: 	$title=~s/\&colon\;/\:/gs;
                   8765: 	if ($title) {
1.599     albertel 8766: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8767: 	}
                   8768: 	$urlsymb=$url;
                   8769:     }
                   8770:     my $title=&metadata($urlsymb,'title');
                   8771:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8772:     return $title;
1.301     www      8773: }
1.613     albertel 8774: 
1.614     albertel 8775: sub get_slot {
                   8776:     my ($which,$cnum,$cdom)=@_;
                   8777:     if (!$cnum || !$cdom) {
1.790     albertel 8778: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8779: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8780: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8781:     }
1.703     albertel 8782:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8783:     my %slotinfo;
                   8784:     if (exists($remembered{$key})) {
                   8785: 	$slotinfo{$which} = $remembered{$key};
                   8786:     } else {
                   8787: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8788: 	&Apache::lonhomework::showhash(%slotinfo);
                   8789: 	my ($tmp)=keys(%slotinfo);
                   8790: 	if ($tmp=~/^error:/) { return (); }
                   8791: 	$remembered{$key} = $slotinfo{$which};
                   8792:     }
1.616     albertel 8793:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8794: 	return %{$slotinfo{$which}};
                   8795:     }
                   8796:     return $slotinfo{$which};
1.614     albertel 8797: }
1.31      www      8798: # ------------------------------------------------- Update symbolic store links
                   8799: 
                   8800: sub symblist {
                   8801:     my ($mapname,%newhash)=@_;
1.438     www      8802:     $mapname=&deversion(&declutter($mapname));
1.31      www      8803:     my %hash;
1.620     albertel 8804:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8805:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8806:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8807: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8808: 		next if ($url eq 'last_known'
                   8809: 			 && $env{'form.no_update_last_known'});
                   8810: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8811: 						    $newhash{$url}->[1],
                   8812: 						    $newhash{$url}->[0]);
1.191     harris41 8813:             }
1.31      www      8814:             if (untie(%hash)) {
                   8815: 		return 'ok';
                   8816:             }
                   8817:         }
                   8818:     }
                   8819:     return 'error';
1.212     www      8820: }
                   8821: 
                   8822: # --------------------------------------------------------------- Verify a symb
                   8823: 
                   8824: sub symbverify {
1.510     www      8825:     my ($symb,$thisurl)=@_;
                   8826:     my $thisfn=$thisurl;
1.439     www      8827:     $thisfn=&declutter($thisfn);
1.215     www      8828: # direct jump to resource in page or to a sequence - will construct own symbs
                   8829:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8830: # check URL part
1.409     www      8831:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8832: 
1.431     www      8833:     unless ($url eq $thisfn) { return 0; }
1.213     www      8834: 
1.216     www      8835:     $symb=&symbclean($symb);
1.510     www      8836:     $thisurl=&deversion($thisurl);
1.439     www      8837:     $thisfn=&deversion($thisfn);
1.213     www      8838: 
                   8839:     my %bighash;
                   8840:     my $okay=0;
1.431     www      8841: 
1.620     albertel 8842:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8843:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8844:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8845:             $thisurl =~ s/\?.+$//;
                   8846:         }
1.510     www      8847:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8848:         unless ($ids) { 
1.510     www      8849:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8850:         }
                   8851:         if ($ids) {
                   8852: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8853: 	    foreach my $id (split(/\,/,$ids)) {
                   8854: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8855:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8856:                    $symb =~ s/\?.+$//;
                   8857:                }
1.216     www      8858:                if (
                   8859:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8860:    eq $symb) { 
1.620     albertel 8861: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8862: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8863: 		       $okay=1; 
                   8864: 		   }
                   8865: 	       }
1.216     www      8866: 	   }
                   8867:         }
1.213     www      8868: 	untie(%bighash);
                   8869:     }
                   8870:     return $okay;
1.31      www      8871: }
                   8872: 
1.210     www      8873: # --------------------------------------------------------------- Clean-up symb
                   8874: 
                   8875: sub symbclean {
                   8876:     my $symb=shift;
1.568     albertel 8877:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8878: # remove version from map
                   8879:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8880: 
1.210     www      8881: # remove version from URL
                   8882:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8883: 
1.507     www      8884: # remove wrapper
                   8885: 
1.510     www      8886:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8887:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8888:     return $symb;
1.409     www      8889: }
                   8890: 
                   8891: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8892: 
                   8893: sub encode_symb {
                   8894:     my ($map,$resid,$url)=@_;
                   8895:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8896: }
1.409     www      8897: 
                   8898: sub decode_symb {
1.568     albertel 8899:     my $symb=shift;
                   8900:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8901:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8902:     return (&fixversion($map),$resid,&fixversion($url));
                   8903: }
                   8904: 
                   8905: sub fixversion {
                   8906:     my $fn=shift;
1.609     banghart 8907:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8908:     my %bighash;
                   8909:     my $uri=&clutter($fn);
1.620     albertel 8910:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8911: # is this cached?
1.599     albertel 8912:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8913:     if (defined($cached)) { return $result; }
                   8914: # unfortunately not cached, or expired
1.620     albertel 8915:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8916: 	    &GDBM_READER(),0640)) {
                   8917:  	if ($bighash{'version_'.$uri}) {
                   8918:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8919:  	    unless (($version eq 'mostrecent') || 
                   8920: 		    ($version==&getversion($uri))) {
1.440     www      8921:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8922:  	    }
                   8923:  	}
                   8924:  	untie %bighash;
1.413     www      8925:     }
1.599     albertel 8926:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8927: }
                   8928: 
                   8929: sub deversion {
                   8930:     my $url=shift;
                   8931:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8932:     return $url;
1.210     www      8933: }
                   8934: 
1.31      www      8935: # ------------------------------------------------------ Return symb list entry
                   8936: 
                   8937: sub symbread {
1.249     www      8938:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8939:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8940:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8941: # no filename provided? try from environment
1.44      www      8942:     unless ($thisfn) {
1.620     albertel 8943:         if ($env{'request.symb'}) {
                   8944: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8945: 	}
1.620     albertel 8946: 	$thisfn=$env{'request.filename'};
1.44      www      8947:     }
1.569     albertel 8948:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8949: # is that filename actually a symb? Verify, clean, and return
                   8950:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8951: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8952: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8953: 	}
1.242     www      8954:     }
1.44      www      8955:     $thisfn=declutter($thisfn);
1.31      www      8956:     my %hash;
1.37      www      8957:     my %bighash;
                   8958:     my $syval='';
1.620     albertel 8959:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8960:         my $targetfn = $thisfn;
1.609     banghart 8961:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8962:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8963:         }
1.687     albertel 8964: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8965: 	    $targetfn=$1;
                   8966: 	}
1.620     albertel 8967:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8968:                       &GDBM_READER(),0640)) {
1.481     raeburn  8969: 	    $syval=$hash{$targetfn};
1.37      www      8970:             untie(%hash);
                   8971:         }
                   8972: # ---------------------------------------------------------- There was an entry
                   8973:         if ($syval) {
1.601     albertel 8974: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8975: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8976: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8977: 		    #return $env{$cache_str}='';
1.601     albertel 8978: 		#}    
                   8979: 		#$syval.=$1;
                   8980: 	    #}
1.37      www      8981:         } else {
                   8982: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8983:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8984:                             &GDBM_READER(),0640)) {
1.37      www      8985: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8986:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8987:               unless ($ids) { 
                   8988:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8989:               }
                   8990:               unless ($ids) {
                   8991: # alias?
                   8992: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8993:               }
1.37      www      8994:               if ($ids) {
                   8995: # ------------------------------------------------------------------- Has ID(s)
                   8996:                  my @possibilities=split(/\,/,$ids);
1.39      www      8997:                  if ($#possibilities==0) {
                   8998: # ----------------------------------------------- There is only one possibility
1.37      www      8999: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9000: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9001: 						    $resid,$thisfn);
1.249     www      9002:                  } elsif (!$donotrecurse) {
1.39      www      9003: # ------------------------------------------ There is more than one possibility
                   9004:                      my $realpossible=0;
1.800     albertel 9005:                      foreach my $id (@possibilities) {
                   9006: 			 my $file=$bighash{'src_'.$id};
1.39      www      9007:                          if (&allowed('bre',$file)) {
1.800     albertel 9008:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9009:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9010: 				$realpossible++;
1.626     albertel 9011:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9012: 						    $resid,$thisfn);
1.39      www      9013:                             }
                   9014: 			 }
1.191     harris41 9015:                      }
1.39      www      9016: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9017:                  } else {
                   9018:                      $syval='';
1.37      www      9019:                  }
                   9020: 	      }
                   9021:               untie(%bighash)
1.481     raeburn  9022:            }
1.31      www      9023:         }
1.62      www      9024:         if ($syval) {
1.620     albertel 9025: 	    return $env{$cache_str}=$syval;
1.62      www      9026:         }
1.31      www      9027:     }
1.949     raeburn  9028:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9029:     return $env{$cache_str}='';
1.31      www      9030: }
                   9031: 
                   9032: # ---------------------------------------------------------- Return random seed
                   9033: 
1.32      www      9034: sub numval {
                   9035:     my $txt=shift;
                   9036:     $txt=~tr/A-J/0-9/;
                   9037:     $txt=~tr/a-j/0-9/;
                   9038:     $txt=~tr/K-T/0-9/;
                   9039:     $txt=~tr/k-t/0-9/;
                   9040:     $txt=~tr/U-Z/0-5/;
                   9041:     $txt=~tr/u-z/0-5/;
                   9042:     $txt=~s/\D//g;
1.564     albertel 9043:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9044:     return int($txt);
1.368     albertel 9045: }
                   9046: 
1.484     albertel 9047: sub numval2 {
                   9048:     my $txt=shift;
                   9049:     $txt=~tr/A-J/0-9/;
                   9050:     $txt=~tr/a-j/0-9/;
                   9051:     $txt=~tr/K-T/0-9/;
                   9052:     $txt=~tr/k-t/0-9/;
                   9053:     $txt=~tr/U-Z/0-5/;
                   9054:     $txt=~tr/u-z/0-5/;
                   9055:     $txt=~s/\D//g;
                   9056:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9057:     my $total;
                   9058:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9059:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9060:     return int($total);
                   9061: }
                   9062: 
1.575     albertel 9063: sub numval3 {
                   9064:     use integer;
                   9065:     my $txt=shift;
                   9066:     $txt=~tr/A-J/0-9/;
                   9067:     $txt=~tr/a-j/0-9/;
                   9068:     $txt=~tr/K-T/0-9/;
                   9069:     $txt=~tr/k-t/0-9/;
                   9070:     $txt=~tr/U-Z/0-5/;
                   9071:     $txt=~tr/u-z/0-5/;
                   9072:     $txt=~s/\D//g;
                   9073:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9074:     my $total;
                   9075:     foreach my $val (@txts) { $total+=$val; }
                   9076:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9077:     return $total;
                   9078: }
                   9079: 
1.675     albertel 9080: sub digest {
                   9081:     my ($data)=@_;
                   9082:     my $digest=&Digest::MD5::md5($data);
                   9083:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9084:     my ($e,$f);
                   9085:     {
                   9086:         use integer;
                   9087:         $e=($a+$b);
                   9088:         $f=($c+$d);
                   9089:         if ($_64bit) {
                   9090:             $e=(($e<<32)>>32);
                   9091:             $f=(($f<<32)>>32);
                   9092:         }
                   9093:     }
                   9094:     if (wantarray) {
                   9095: 	return ($e,$f);
                   9096:     } else {
                   9097: 	my $g;
                   9098: 	{
                   9099: 	    use integer;
                   9100: 	    $g=($e+$f);
                   9101: 	    if ($_64bit) {
                   9102: 		$g=(($g<<32)>>32);
                   9103: 	    }
                   9104: 	}
                   9105: 	return $g;
                   9106:     }
                   9107: }
                   9108: 
1.368     albertel 9109: sub latest_rnd_algorithm_id {
1.675     albertel 9110:     return '64bit5';
1.366     albertel 9111: }
1.32      www      9112: 
1.503     albertel 9113: sub get_rand_alg {
                   9114:     my ($courseid)=@_;
1.790     albertel 9115:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9116:     if ($courseid) {
1.620     albertel 9117: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9118:     }
                   9119:     return &latest_rnd_algorithm_id();
                   9120: }
                   9121: 
1.562     albertel 9122: sub validCODE {
                   9123:     my ($CODE)=@_;
                   9124:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9125:     return 0;
                   9126: }
                   9127: 
1.491     albertel 9128: sub getCODE {
1.620     albertel 9129:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9130:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9131: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9132: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9133: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9134:     }
                   9135:     return undef;
                   9136: }
                   9137: 
1.31      www      9138: sub rndseed {
1.155     albertel 9139:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9140:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9141:     if (!defined($symb)) {
1.366     albertel 9142: 	unless ($symb=$wsymb) { return time; }
                   9143:     }
                   9144:     if (!$courseid) { $courseid=$wcourseid; }
                   9145:     if (!$domain) { $domain=$wdomain; }
                   9146:     if (!$username) { $username=$wusername }
1.503     albertel 9147:     my $which=&get_rand_alg();
1.803     albertel 9148: 
1.491     albertel 9149:     if (defined(&getCODE())) {
1.675     albertel 9150: 	if ($which eq '64bit5') {
                   9151: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9152: 	} elsif ($which eq '64bit4') {
1.575     albertel 9153: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9154: 	} else {
                   9155: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9156: 	}
1.675     albertel 9157:     } elsif ($which eq '64bit5') {
                   9158: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9159:     } elsif ($which eq '64bit4') {
                   9160: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9161:     } elsif ($which eq '64bit3') {
                   9162: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9163:     } elsif ($which eq '64bit2') {
                   9164: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9165:     } elsif ($which eq '64bit') {
                   9166: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9167:     }
                   9168:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9169: }
                   9170: 
                   9171: sub rndseed_32bit {
                   9172:     my ($symb,$courseid,$domain,$username)=@_;
                   9173:     {
                   9174: 	use integer;
                   9175: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9176: 	my $symbseed=numval($symb) << 22;
                   9177: 	my $namechck=unpack("%32C*",$username) << 17;
                   9178: 	my $nameseed=numval($username) << 12;
                   9179: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9180: 	my $courseseed=unpack("%32C*",$courseid);
                   9181: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9182: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9183: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9184: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9185: 	return $num;
                   9186:     }
                   9187: }
                   9188: 
                   9189: sub rndseed_64bit {
                   9190:     my ($symb,$courseid,$domain,$username)=@_;
                   9191:     {
                   9192: 	use integer;
                   9193: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9194: 	my $symbseed=numval($symb) << 10;
                   9195: 	my $namechck=unpack("%32S*",$username);
                   9196: 	
                   9197: 	my $nameseed=numval($username) << 21;
                   9198: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9199: 	my $courseseed=unpack("%32S*",$courseid);
                   9200: 	
                   9201: 	my $num1=$symbchck+$symbseed+$namechck;
                   9202: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9203: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9204: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9205: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9206: 	return "$num1,$num2";
1.155     albertel 9207:     }
1.366     albertel 9208: }
                   9209: 
1.443     albertel 9210: sub rndseed_64bit2 {
                   9211:     my ($symb,$courseid,$domain,$username)=@_;
                   9212:     {
                   9213: 	use integer;
                   9214: 	# strings need to be an even # of cahracters long, it it is odd the
                   9215:         # last characters gets thrown away
                   9216: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9217: 	my $symbseed=numval($symb) << 10;
                   9218: 	my $namechck=unpack("%32S*",$username.' ');
                   9219: 	
                   9220: 	my $nameseed=numval($username) << 21;
1.501     albertel 9221: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9222: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9223: 	
                   9224: 	my $num1=$symbchck+$symbseed+$namechck;
                   9225: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9226: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9227: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9228: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9229: 	return "$num1,$num2";
                   9230:     }
                   9231: }
                   9232: 
                   9233: sub rndseed_64bit3 {
                   9234:     my ($symb,$courseid,$domain,$username)=@_;
                   9235:     {
                   9236: 	use integer;
                   9237: 	# strings need to be an even # of cahracters long, it it is odd the
                   9238:         # last characters gets thrown away
                   9239: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9240: 	my $symbseed=numval2($symb) << 10;
                   9241: 	my $namechck=unpack("%32S*",$username.' ');
                   9242: 	
                   9243: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9244: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9245: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9246: 	
                   9247: 	my $num1=$symbchck+$symbseed+$namechck;
                   9248: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9249: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9250: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9251: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9252: 	
1.503     albertel 9253: 	return "$num1:$num2";
1.443     albertel 9254:     }
                   9255: }
                   9256: 
1.575     albertel 9257: sub rndseed_64bit4 {
                   9258:     my ($symb,$courseid,$domain,$username)=@_;
                   9259:     {
                   9260: 	use integer;
                   9261: 	# strings need to be an even # of cahracters long, it it is odd the
                   9262:         # last characters gets thrown away
                   9263: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9264: 	my $symbseed=numval3($symb) << 10;
                   9265: 	my $namechck=unpack("%32S*",$username.' ');
                   9266: 	
                   9267: 	my $nameseed=numval3($username) << 21;
                   9268: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9269: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9270: 	
                   9271: 	my $num1=$symbchck+$symbseed+$namechck;
                   9272: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9273: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9274: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9275: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9276: 	
                   9277: 	return "$num1:$num2";
                   9278:     }
                   9279: }
                   9280: 
1.675     albertel 9281: sub rndseed_64bit5 {
                   9282:     my ($symb,$courseid,$domain,$username)=@_;
                   9283:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9284:     return "$num1:$num2";
                   9285: }
                   9286: 
1.366     albertel 9287: sub rndseed_CODE_64bit {
                   9288:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9289:     {
1.366     albertel 9290: 	use integer;
1.443     albertel 9291: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9292: 	my $symbseed=numval2($symb);
1.491     albertel 9293: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9294: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9295: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9296: 	my $num1=$symbseed+$CODEchck;
                   9297: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9298: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9299: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9300: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9301: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9302: 	return "$num1:$num2";
1.366     albertel 9303:     }
                   9304: }
                   9305: 
1.575     albertel 9306: sub rndseed_CODE_64bit4 {
                   9307:     my ($symb,$courseid,$domain,$username)=@_;
                   9308:     {
                   9309: 	use integer;
                   9310: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9311: 	my $symbseed=numval3($symb);
                   9312: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9313: 	my $CODEseed=numval3(&getCODE());
                   9314: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9315: 	my $num1=$symbseed+$CODEchck;
                   9316: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9317: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9318: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9319: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9320: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9321: 	return "$num1:$num2";
                   9322:     }
                   9323: }
                   9324: 
1.675     albertel 9325: sub rndseed_CODE_64bit5 {
                   9326:     my ($symb,$courseid,$domain,$username)=@_;
                   9327:     my $code = &getCODE();
                   9328:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9329:     return "$num1:$num2";
                   9330: }
                   9331: 
1.366     albertel 9332: sub setup_random_from_rndseed {
                   9333:     my ($rndseed)=@_;
1.503     albertel 9334:     if ($rndseed =~/([,:])/) {
                   9335: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9336: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9337:     } else {
                   9338: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9339:     }
1.36      albertel 9340: }
                   9341: 
1.474     albertel 9342: sub latest_receipt_algorithm_id {
1.835     albertel 9343:     return 'receipt3';
1.474     albertel 9344: }
                   9345: 
1.480     www      9346: sub recunique {
                   9347:     my $fucourseid=shift;
                   9348:     my $unique;
1.835     albertel 9349:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9350: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9351: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9352:     } else {
                   9353: 	$unique=$perlvar{'lonReceipt'};
                   9354:     }
                   9355:     return unpack("%32C*",$unique);
                   9356: }
                   9357: 
                   9358: sub recprefix {
                   9359:     my $fucourseid=shift;
                   9360:     my $prefix;
1.835     albertel 9361:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9362: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9363: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9364:     } else {
                   9365: 	$prefix=$perlvar{'lonHostID'};
                   9366:     }
                   9367:     return unpack("%32C*",$prefix);
                   9368: }
                   9369: 
1.76      www      9370: sub ireceipt {
1.474     albertel 9371:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9372: 
                   9373:     my $return =&recprefix($fucourseid).'-';
                   9374: 
                   9375:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9376: 	$env{'request.state'} eq 'construct') {
                   9377: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9378: 	return $return;
                   9379:     }
                   9380: 
1.76      www      9381:     my $cuname=unpack("%32C*",$funame);
                   9382:     my $cudom=unpack("%32C*",$fudom);
                   9383:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9384:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9385:     my $cunique=&recunique($fucourseid);
1.474     albertel 9386:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9387:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9388: 
1.790     albertel 9389: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9390: 			       
                   9391: 	$return.= ($cunique%$cuname+
                   9392: 		   $cunique%$cudom+
                   9393: 		   $cusymb%$cuname+
                   9394: 		   $cusymb%$cudom+
                   9395: 		   $cucourseid%$cuname+
                   9396: 		   $cucourseid%$cudom+
                   9397: 		   $cpart%$cuname+
                   9398: 		   $cpart%$cudom);
                   9399:     } else {
                   9400: 	$return.= ($cunique%$cuname+
                   9401: 		   $cunique%$cudom+
                   9402: 		   $cusymb%$cuname+
                   9403: 		   $cusymb%$cudom+
                   9404: 		   $cucourseid%$cuname+
                   9405: 		   $cucourseid%$cudom);
                   9406:     }
                   9407:     return $return;
1.76      www      9408: }
                   9409: 
                   9410: sub receipt {
1.474     albertel 9411:     my ($part)=@_;
1.790     albertel 9412:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9413:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9414: }
1.260     ng       9415: 
1.790     albertel 9416: sub whichuser {
                   9417:     my ($passedsymb)=@_;
                   9418:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9419:     if (defined($env{'form.grade_symb'})) {
                   9420: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9421: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9422: 	if (!$allowed &&
                   9423: 	    exists($env{'request.course.sec'}) &&
                   9424: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9425: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9426: 			      '/'.$env{'request.course.sec'});
                   9427: 	}
                   9428: 	if ($allowed) {
                   9429: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9430: 	    $courseid=$tmp_courseid;
                   9431: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9432: 	    ($name)=&get_env_multiple('form.grade_username');
                   9433: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9434: 	}
                   9435:     }
                   9436:     if (!$passedsymb) {
                   9437: 	$symb=&symbread();
                   9438:     } else {
                   9439: 	$symb=$passedsymb;
                   9440:     }
                   9441:     $courseid=$env{'request.course.id'};
                   9442:     $domain=$env{'user.domain'};
                   9443:     $name=$env{'user.name'};
                   9444:     if ($name eq 'public' && $domain eq 'public') {
                   9445: 	if (!defined($env{'form.username'})) {
                   9446: 	    $env{'form.username'}.=time.rand(10000000);
                   9447: 	}
                   9448: 	$name.=$env{'form.username'};
                   9449:     }
                   9450:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9451: 
                   9452: }
                   9453: 
1.36      albertel 9454: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9455: # returns either the contents of the file or 
                   9456: # -1 if the file doesn't exist
1.481     raeburn  9457: #
                   9458: # if the target is a file that was uploaded via DOCS, 
                   9459: # a check will be made to see if a current copy exists on the local server,
                   9460: # if it does this will be served, otherwise a copy will be retrieved from
                   9461: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9462: # the local server.   
1.472     albertel 9463: 
1.36      albertel 9464: sub getfile {
1.538     albertel 9465:     my ($file) = @_;
1.609     banghart 9466:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9467:     &repcopy($file);
                   9468:     return &readfile($file);
                   9469: }
                   9470: 
                   9471: sub repcopy_userfile {
                   9472:     my ($file)=@_;
1.609     banghart 9473:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9474:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9475:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9476: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9477:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9478:     if (-e "$file") {
1.828     www      9479: # we already have a local copy, check it out
1.538     albertel 9480: 	my @fileinfo = stat($file);
1.828     www      9481: 	my $rtncode;
                   9482: 	my $info;
1.538     albertel 9483: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9484: 	if ($lwpresp ne 'ok') {
1.828     www      9485: # there is no such file anymore, even though we had a local copy
1.482     albertel 9486: 	    if ($rtncode eq '404') {
1.538     albertel 9487: 		unlink($file);
1.482     albertel 9488: 	    }
                   9489: 	    return -1;
                   9490: 	}
                   9491: 	if ($info < $fileinfo[9]) {
1.828     www      9492: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9493: 	    return 'ok';
1.828     www      9494: 	} else {
                   9495: # the file is outdated, get rid of it
                   9496: 	    unlink($file);
1.482     albertel 9497: 	}
1.828     www      9498:     }
                   9499: # one way or the other, at this point, we don't have the file
                   9500: # construct the correct path for the file
                   9501:     my @parts = ($cdom,$cnum); 
                   9502:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9503: 	push @parts, split(/\//,$1);
                   9504:     }
                   9505:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9506:     foreach my $part (@parts) {
                   9507: 	$path .= '/'.$part;
                   9508: 	if (!-e $path) {
                   9509: 	    mkdir($path,0770);
1.482     albertel 9510: 	}
                   9511:     }
1.828     www      9512: # now the path exists for sure
                   9513: # get a user agent
                   9514:     my $ua=new LWP::UserAgent;
                   9515:     my $transferfile=$file.'.in.transfer';
                   9516: # FIXME: this should flock
                   9517:     if (-e $transferfile) { return 'ok'; }
                   9518:     my $request;
                   9519:     $uri=~s/^\///;
1.980     raeburn  9520:     my $homeserver = &homeserver($cnum,$cdom);
                   9521:     my $protocol = $protocol{$homeserver};
                   9522:     $protocol = 'http' if ($protocol ne 'https');
                   9523:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9524:     my $response=$ua->request($request,$transferfile);
                   9525: # did it work?
                   9526:     if ($response->is_error()) {
                   9527: 	unlink($transferfile);
                   9528: 	&logthis("Userfile repcopy failed for $uri");
                   9529: 	return -1;
                   9530:     }
                   9531: # worked, rename the transfer file
                   9532:     rename($transferfile,$file);
1.607     raeburn  9533:     return 'ok';
1.481     raeburn  9534: }
                   9535: 
1.517     albertel 9536: sub tokenwrapper {
                   9537:     my $uri=shift;
1.980     raeburn  9538:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9539:     $uri=~s|^/||;
1.620     albertel 9540:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9541:     my $token=$1;
1.552     albertel 9542:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9543:     if ($udom && $uname && $file) {
                   9544: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9545:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9546:         my $homeserver = &homeserver($uname,$udom);
                   9547:         my $protocol = $protocol{$homeserver};
                   9548:         $protocol = 'http' if ($protocol ne 'https');
                   9549:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9550:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9551:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9552:     } else {
                   9553:         return '/adm/notfound.html';
                   9554:     }
                   9555: }
                   9556: 
1.828     www      9557: # call with reqtype HEAD: get last modification time
                   9558: # call with reqtype GET: get the file contents
                   9559: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9560: #
1.481     raeburn  9561: sub getuploaded {
                   9562:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9563:     $uri=~s/^\///;
1.980     raeburn  9564:     my $homeserver = &homeserver($cnum,$cdom);
                   9565:     my $protocol = $protocol{$homeserver};
                   9566:     $protocol = 'http' if ($protocol ne 'https');
                   9567:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9568:     my $ua=new LWP::UserAgent;
                   9569:     my $request=new HTTP::Request($reqtype,$uri);
                   9570:     my $response=$ua->request($request);
                   9571:     $$rtncode = $response->code;
1.482     albertel 9572:     if (! $response->is_success()) {
                   9573: 	return 'failed';
                   9574:     }      
                   9575:     if ($reqtype eq 'HEAD') {
1.486     www      9576: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9577:     } elsif ($reqtype eq 'GET') {
                   9578: 	$$info = $response->content;
1.472     albertel 9579:     }
1.482     albertel 9580:     return 'ok';
1.36      albertel 9581: }
                   9582: 
1.481     raeburn  9583: sub readfile {
                   9584:     my $file = shift;
                   9585:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9586:     my $fh;
                   9587:     open($fh,"<$file");
                   9588:     my $a='';
1.800     albertel 9589:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9590:     return $a;
                   9591: }
                   9592: 
1.36      albertel 9593: sub filelocation {
1.590     banghart 9594:     my ($dir,$file) = @_;
                   9595:     my $location;
                   9596:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9597: 
                   9598:     if ($file =~ m-^/adm/-) {
                   9599: 	$file=~s-^/adm/wrapper/-/-;
                   9600: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9601:     }
1.882     albertel 9602: 
1.590     banghart 9603:     if ($file=~m:^/~:) { # is a contruction space reference
                   9604:         $location = $file;
                   9605:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9606:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9607: 	# is a correct contruction space reference
                   9608:         $location = $file;
1.956     raeburn  9609:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9610:         $location = $file;
1.609     banghart 9611:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9612:         my ($udom,$uname,$filename)=
1.811     albertel 9613:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9614:         my $home=&homeserver($uname,$udom);
                   9615:         my $is_me=0;
                   9616:         my @ids=&current_machine_ids();
                   9617:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9618:         if ($is_me) {
1.955     raeburn  9619:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9620:         } else {
                   9621:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9622:   	      $udom.'/'.$uname.'/'.$filename;
                   9623:         }
1.882     albertel 9624:     } elsif ($file =~ m-^/adm/-) {
                   9625: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9626:     } else {
                   9627:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9628:         $file=~s:^/res/:/:;
                   9629:         if ( !( $file =~ m:^/:) ) {
                   9630:             $location = $dir. '/'.$file;
                   9631:         } else {
                   9632:             $location = '/home/httpd/html/res'.$file;
                   9633:         }
1.59      albertel 9634:     }
1.590     banghart 9635:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9636:     while ($location=~m{/\.\./}) {
                   9637: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9638: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9639: 	} else {
                   9640: 	    $location=~ s{/\.\./}{/}g;
                   9641: 	}
                   9642:     } #remove dir/..
1.590     banghart 9643:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9644:     return $location;
1.46      www      9645: }
1.36      albertel 9646: 
1.46      www      9647: sub hreflocation {
                   9648:     my ($dir,$file)=@_;
1.980     raeburn  9649:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9650: 	$file=filelocation($dir,$file);
1.700     albertel 9651:     } elsif ($file=~m-^/adm/-) {
                   9652: 	$file=~s-^/adm/wrapper/-/-;
                   9653: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9654:     }
                   9655:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9656: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9657:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9658: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9659:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9660: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9661: 	    -/uploaded/$1/$2/-x;
1.46      www      9662:     }
1.913     albertel 9663:     if ($file=~ m{^/userfiles/}) {
                   9664: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9665:     }
1.462     albertel 9666:     return $file;
1.465     albertel 9667: }
                   9668: 
                   9669: sub current_machine_domains {
1.853     albertel 9670:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9671: }
                   9672: 
                   9673: sub machine_domains {
                   9674:     my ($hostname) = @_;
1.465     albertel 9675:     my @domains;
1.838     albertel 9676:     my %hostname = &all_hostnames();
1.465     albertel 9677:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9678: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9679: 	if ($hostname eq $name) {
1.844     albertel 9680: 	    push(@domains,&host_domain($id));
1.465     albertel 9681: 	}
                   9682:     }
                   9683:     return @domains;
                   9684: }
                   9685: 
                   9686: sub current_machine_ids {
1.853     albertel 9687:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9688: }
                   9689: 
                   9690: sub machine_ids {
                   9691:     my ($hostname) = @_;
                   9692:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9693:     my @ids;
1.888     albertel 9694:     my %name_to_host = &all_names();
1.889     albertel 9695:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9696: 	return @{ $name_to_host{$hostname} };
                   9697:     }
                   9698:     return;
1.31      www      9699: }
                   9700: 
1.824     raeburn  9701: sub additional_machine_domains {
                   9702:     my @domains;
                   9703:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9704:     while( my $line = <$fh>) {
                   9705:         $line =~ s/\s//g;
                   9706:         push(@domains,$line);
                   9707:     }
                   9708:     return @domains;
                   9709: }
                   9710: 
                   9711: sub default_login_domain {
                   9712:     my $domain = $perlvar{'lonDefDomain'};
                   9713:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9714:     foreach my $posdom (&current_machine_domains(),
                   9715:                         &additional_machine_domains()) {
                   9716:         if (lc($posdom) eq lc($testdomain)) {
                   9717:             $domain=$posdom;
                   9718:             last;
                   9719:         }
                   9720:     }
                   9721:     return $domain;
                   9722: }
                   9723: 
1.31      www      9724: # ------------------------------------------------------------- Declutters URLs
                   9725: 
                   9726: sub declutter {
                   9727:     my $thisfn=shift;
1.569     albertel 9728:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9729:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9730:     $thisfn=~s/^\///;
1.697     albertel 9731:     $thisfn=~s|^adm/wrapper/||;
                   9732:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9733:     $thisfn=~s/^res\///;
1.1032    raeburn  9734:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9735:         $thisfn=~s/\?.+$//;
                   9736:     }
1.268     www      9737:     return $thisfn;
                   9738: }
                   9739: 
                   9740: # ------------------------------------------------------------- Clutter up URLs
                   9741: 
                   9742: sub clutter {
                   9743:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9744:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9745: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9746:        $thisfn='/res'.$thisfn; 
                   9747:     }
1.1031    raeburn  9748:     if ($thisfn !~m|^/adm|) {
                   9749: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9750: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9751: 	} else {
                   9752: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9753: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9754: 	    if ($embstyle eq 'ssi'
                   9755: 		|| ($embstyle eq 'hdn')
                   9756: 		|| ($embstyle eq 'rat')
                   9757: 		|| ($embstyle eq 'prv')
                   9758: 		|| ($embstyle eq 'ign')) {
                   9759: 		#do nothing with these
                   9760: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9761: 		|| ($embstyle eq 'emb')
                   9762: 		|| ($embstyle eq 'wrp')) {
                   9763: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9764: 	    } elsif ($embstyle eq 'unk'
                   9765: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9766: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9767: 	    } else {
1.718     www      9768: #		&logthis("Got a blank emb style");
1.695     albertel 9769: 	    }
1.694     albertel 9770: 	}
                   9771:     }
1.31      www      9772:     return $thisfn;
1.12      www      9773: }
                   9774: 
1.787     albertel 9775: sub clutter_with_no_wrapper {
                   9776:     my $uri = &clutter(shift);
                   9777:     if ($uri =~ m-^/adm/-) {
                   9778: 	$uri =~ s-^/adm/wrapper/-/-;
                   9779: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9780:     }
                   9781:     return $uri;
                   9782: }
                   9783: 
1.557     albertel 9784: sub freeze_escape {
                   9785:     my ($value)=@_;
                   9786:     if (ref($value)) {
                   9787: 	$value=&nfreeze($value);
                   9788: 	return '__FROZEN__'.&escape($value);
                   9789:     }
                   9790:     return &escape($value);
                   9791: }
                   9792: 
1.11      www      9793: 
1.557     albertel 9794: sub thaw_unescape {
                   9795:     my ($value)=@_;
                   9796:     if ($value =~ /^__FROZEN__/) {
                   9797: 	substr($value,0,10,undef);
                   9798: 	$value=&unescape($value);
                   9799: 	return &thaw($value);
                   9800:     }
                   9801:     return &unescape($value);
                   9802: }
                   9803: 
1.436     albertel 9804: sub correct_line_ends {
                   9805:     my ($result)=@_;
                   9806:     $$result =~s/\r\n/\n/mg;
                   9807:     $$result =~s/\r/\n/mg;
1.415     albertel 9808: }
1.1       albertel 9809: # ================================================================ Main Program
                   9810: 
1.184     www      9811: sub goodbye {
1.204     albertel 9812:    &logthis("Starting Shut down");
1.443     albertel 9813: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9814:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9815: #converted
1.599     albertel 9816: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9817:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9818: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9819: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9820: #1.1 only
1.870     albertel 9821: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9822: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9823: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9824: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9825:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9826:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9827:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9828:    &flushcourselogs();
                   9829:    &logthis("Shutting down");
                   9830: }
                   9831: 
1.852     albertel 9832: sub get_dns {
1.869     albertel 9833:     my ($url,$func,$ignore_cache) = @_;
                   9834:     if (!$ignore_cache) {
                   9835: 	my ($content,$cached)=
                   9836: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9837: 	if ($cached) {
                   9838: 	    &$func($content);
                   9839: 	    return;
                   9840: 	}
                   9841:     }
                   9842: 
                   9843:     my %alldns;
1.852     albertel 9844:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9845:     foreach my $dns (<$config>) {
                   9846: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9847:         my $line = $1;
                   9848:         my ($host,$protocol) = split(/:/,$line);
                   9849:         if ($protocol ne 'https') {
                   9850:             $protocol = 'http';
                   9851:         }
                   9852: 	$alldns{$host} = $protocol;
1.869     albertel 9853:     }
                   9854:     while (%alldns) {
                   9855: 	my ($dns) = keys(%alldns);
1.852     albertel 9856: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9857: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9858: 	my $response=$ua->request($request);
1.979     raeburn  9859:         delete($alldns{$dns});
1.852     albertel 9860: 	next if ($response->is_error());
                   9861: 	my @content = split("\n",$response->content);
1.869     albertel 9862: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9863: 	&$func(\@content);
1.869     albertel 9864: 	return;
1.852     albertel 9865:     }
                   9866:     close($config);
1.871     albertel 9867:     my $which = (split('/',$url))[3];
                   9868:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9869:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9870:     my @content = <$config>;
                   9871:     &$func(\@content);
                   9872:     return;
1.852     albertel 9873: }
1.327     albertel 9874: # ------------------------------------------------------------ Read domain file
                   9875: {
1.852     albertel 9876:     my $loaded;
1.846     albertel 9877:     my %domain;
                   9878: 
1.852     albertel 9879:     sub parse_domain_tab {
                   9880: 	my ($lines) = @_;
                   9881: 	foreach my $line (@$lines) {
                   9882: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9883: 
1.846     albertel 9884: 	    chomp($line);
1.852     albertel 9885: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9886: 	    my %this_domain;
                   9887: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9888: 			       'lang_def', 'city', 'longi', 'lati',
                   9889: 			       'primary') {
                   9890: 		$this_domain{$field} = shift(@elements);
                   9891: 	    }
                   9892: 	    $domain{$name} = \%this_domain;
1.852     albertel 9893: 	}
                   9894:     }
1.864     albertel 9895: 
                   9896:     sub reset_domain_info {
                   9897: 	undef($loaded);
                   9898: 	undef(%domain);
                   9899:     }
                   9900: 
1.852     albertel 9901:     sub load_domain_tab {
1.869     albertel 9902: 	my ($ignore_cache) = @_;
                   9903: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9904: 	my $fh;
                   9905: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9906: 	    my @lines = <$fh>;
                   9907: 	    &parse_domain_tab(\@lines);
1.448     albertel 9908: 	}
1.852     albertel 9909: 	close($fh);
                   9910: 	$loaded = 1;
1.327     albertel 9911:     }
1.846     albertel 9912: 
                   9913:     sub domain {
1.852     albertel 9914: 	&load_domain_tab() if (!$loaded);
                   9915: 
1.846     albertel 9916: 	my ($name,$what) = @_;
                   9917: 	return if ( !exists($domain{$name}) );
                   9918: 
                   9919: 	if (!$what) {
                   9920: 	    return $domain{$name}{'description'};
                   9921: 	}
                   9922: 	return $domain{$name}{$what};
                   9923:     }
1.974     raeburn  9924: 
                   9925:     sub domain_info {
                   9926:         &load_domain_tab() if (!$loaded);
                   9927:         return %domain;
                   9928:     }
                   9929: 
1.327     albertel 9930: }
                   9931: 
                   9932: 
1.1       albertel 9933: # ------------------------------------------------------------- Read hosts file
                   9934: {
1.838     albertel 9935:     my %hostname;
1.844     albertel 9936:     my %hostdom;
1.845     albertel 9937:     my %libserv;
1.852     albertel 9938:     my $loaded;
1.888     albertel 9939:     my %name_to_host;
1.1056.4.6  raeburn  9940:     my %internetdom;
1.852     albertel 9941: 
                   9942:     sub parse_hosts_tab {
                   9943: 	my ($file) = @_;
                   9944: 	foreach my $configline (@$file) {
                   9945: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9946: 	    next if ($configline =~ /^\^/);
                   9947: 	    chomp($configline);
1.1056.4.6  raeburn  9948: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 9949: 	    $name=~s/\s//g;
                   9950: 	    if ($id && $domain && $role && $name) {
                   9951: 		$hostname{$id}=$name;
1.888     albertel 9952: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9953: 		$hostdom{$id}=$domain;
                   9954: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9955:                 if (defined($protocol)) {
                   9956:                     if ($protocol eq 'https') {
                   9957:                         $protocol{$id} = $protocol;
                   9958:                     } else {
                   9959:                         $protocol{$id} = 'http'; 
                   9960:                     }
1.968     raeburn  9961:                 } else {
1.969     raeburn  9962:                     $protocol{$id} = 'http';
1.968     raeburn  9963:                 }
1.1056.4.6  raeburn  9964:                 if (defined($intdom)) {
                   9965:                     $internetdom{$id} = $intdom;
                   9966:                 }
1.852     albertel 9967: 	    }
                   9968: 	}
                   9969:     }
1.864     albertel 9970:     
                   9971:     sub reset_hosts_info {
1.897     albertel 9972: 	&purge_remembered();
1.864     albertel 9973: 	&reset_domain_info();
                   9974: 	&reset_hosts_ip_info();
1.892     albertel 9975: 	undef(%name_to_host);
1.864     albertel 9976: 	undef(%hostname);
                   9977: 	undef(%hostdom);
                   9978: 	undef(%libserv);
                   9979: 	undef($loaded);
                   9980:     }
1.1       albertel 9981: 
1.852     albertel 9982:     sub load_hosts_tab {
1.869     albertel 9983: 	my ($ignore_cache) = @_;
                   9984: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9985: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9986: 	my @config = <$config>;
                   9987: 	&parse_hosts_tab(\@config);
                   9988: 	close($config);
                   9989: 	$loaded=1;
1.1       albertel 9990:     }
1.852     albertel 9991: 
1.838     albertel 9992:     sub hostname {
1.852     albertel 9993: 	&load_hosts_tab() if (!$loaded);
                   9994: 
1.838     albertel 9995: 	my ($lonid) = @_;
                   9996: 	return $hostname{$lonid};
                   9997:     }
1.845     albertel 9998: 
1.838     albertel 9999:     sub all_hostnames {
1.852     albertel 10000: 	&load_hosts_tab() if (!$loaded);
                   10001: 
1.838     albertel 10002: 	return %hostname;
                   10003:     }
1.845     albertel 10004: 
1.888     albertel 10005:     sub all_names {
                   10006: 	&load_hosts_tab() if (!$loaded);
                   10007: 
                   10008: 	return %name_to_host;
                   10009:     }
                   10010: 
1.974     raeburn  10011:     sub all_host_domain {
                   10012:         &load_hosts_tab() if (!$loaded);
                   10013:         return %hostdom;
                   10014:     }
                   10015: 
1.845     albertel 10016:     sub is_library {
1.852     albertel 10017: 	&load_hosts_tab() if (!$loaded);
                   10018: 
1.845     albertel 10019: 	return exists($libserv{$_[0]});
                   10020:     }
                   10021: 
                   10022:     sub all_library {
1.852     albertel 10023: 	&load_hosts_tab() if (!$loaded);
                   10024: 
1.845     albertel 10025: 	return %libserv;
                   10026:     }
                   10027: 
1.1056.4.2  raeburn  10028:     sub unique_library {
                   10029:         #2x reverse removes all hostnames that appear more than once
                   10030:         my %unique = reverse &all_library();
                   10031:         return reverse %unique;
                   10032:     }
                   10033: 
1.841     albertel 10034:     sub get_servers {
1.852     albertel 10035: 	&load_hosts_tab() if (!$loaded);
                   10036: 
1.841     albertel 10037: 	my ($domain,$type) = @_;
                   10038: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10039: 	                                          : %hostname;
                   10040: 	my %result;
1.842     albertel 10041: 	if (ref($domain) eq 'ARRAY') {
                   10042: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10043: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10044: 		    $result{$host} = $hostname;
                   10045: 		}
                   10046: 	    }
                   10047: 	} else {
                   10048: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10049: 		if ($hostdom{$host} eq $domain) {
                   10050: 		    $result{$host} = $hostname;
                   10051: 		}
1.841     albertel 10052: 	    }
                   10053: 	}
                   10054: 	return %result;
                   10055:     }
1.845     albertel 10056: 
1.1056.4.2  raeburn  10057:     sub get_unique_servers {
                   10058:         my %unique = reverse &get_servers(@_);
                   10059:         return reverse %unique;
                   10060:     }
                   10061: 
1.844     albertel 10062:     sub host_domain {
1.852     albertel 10063: 	&load_hosts_tab() if (!$loaded);
                   10064: 
1.844     albertel 10065: 	my ($lonid) = @_;
                   10066: 	return $hostdom{$lonid};
                   10067:     }
                   10068: 
1.841     albertel 10069:     sub all_domains {
1.852     albertel 10070: 	&load_hosts_tab() if (!$loaded);
                   10071: 
1.841     albertel 10072: 	my %seen;
                   10073: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10074: 	return @uniq;
                   10075:     }
1.1056.4.3  raeburn  10076: 
                   10077:     sub internet_dom {
                   10078:         &load_hosts_tab() if (!$loaded);
                   10079: 
                   10080:         my ($lonid) = @_;
                   10081:         return $internetdom{$lonid};
                   10082:     }
1.1       albertel 10083: }
                   10084: 
1.847     albertel 10085: { 
                   10086:     my %iphost;
1.856     albertel 10087:     my %name_to_ip;
                   10088:     my %lonid_to_ip;
1.869     albertel 10089: 
1.847     albertel 10090:     sub get_hosts_from_ip {
                   10091: 	my ($ip) = @_;
                   10092: 	my %iphosts = &get_iphost();
                   10093: 	if (ref($iphosts{$ip})) {
                   10094: 	    return @{$iphosts{$ip}};
                   10095: 	}
                   10096: 	return;
1.839     albertel 10097:     }
1.864     albertel 10098:     
                   10099:     sub reset_hosts_ip_info {
                   10100: 	undef(%iphost);
                   10101: 	undef(%name_to_ip);
                   10102: 	undef(%lonid_to_ip);
                   10103:     }
1.856     albertel 10104: 
                   10105:     sub get_host_ip {
                   10106: 	my ($lonid) = @_;
                   10107: 	if (exists($lonid_to_ip{$lonid})) {
                   10108: 	    return $lonid_to_ip{$lonid};
                   10109: 	}
                   10110: 	my $name=&hostname($lonid);
                   10111:    	my $ip = gethostbyname($name);
                   10112: 	return if (!$ip || length($ip) ne 4);
                   10113: 	$ip=inet_ntoa($ip);
                   10114: 	$name_to_ip{$name}   = $ip;
                   10115: 	$lonid_to_ip{$lonid} = $ip;
                   10116: 	return $ip;
                   10117:     }
1.847     albertel 10118:     
                   10119:     sub get_iphost {
1.869     albertel 10120: 	my ($ignore_cache) = @_;
1.894     albertel 10121: 
1.869     albertel 10122: 	if (!$ignore_cache) {
                   10123: 	    if (%iphost) {
                   10124: 		return %iphost;
                   10125: 	    }
                   10126: 	    my ($ip_info,$cached)=
                   10127: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10128: 	    if ($cached) {
                   10129: 		%iphost      = %{$ip_info->[0]};
                   10130: 		%name_to_ip  = %{$ip_info->[1]};
                   10131: 		%lonid_to_ip = %{$ip_info->[2]};
                   10132: 		return %iphost;
                   10133: 	    }
                   10134: 	}
1.894     albertel 10135: 
                   10136: 	# get yesterday's info for fallback
                   10137: 	my %old_name_to_ip;
                   10138: 	my ($ip_info,$cached)=
                   10139: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10140: 	if ($cached) {
                   10141: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10142: 	}
                   10143: 
1.888     albertel 10144: 	my %name_to_host = &all_names();
                   10145: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10146: 	    my $ip;
                   10147: 	    if (!exists($name_to_ip{$name})) {
                   10148: 		$ip = gethostbyname($name);
                   10149: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10150: 		    if (defined($old_name_to_ip{$name})) {
                   10151: 			$ip = $old_name_to_ip{$name};
                   10152: 			&logthis("Can't find $name defaulting to old $ip");
                   10153: 		    } else {
                   10154: 			&logthis("Name $name no IP found");
                   10155: 			next;
                   10156: 		    }
                   10157: 		} else {
                   10158: 		    $ip=inet_ntoa($ip);
1.847     albertel 10159: 		}
                   10160: 		$name_to_ip{$name} = $ip;
                   10161: 	    } else {
                   10162: 		$ip = $name_to_ip{$name};
1.653     albertel 10163: 	    }
1.888     albertel 10164: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10165: 		$lonid_to_ip{$id} = $ip;
                   10166: 	    }
                   10167: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10168: 	}
1.869     albertel 10169: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10170: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10171: 				      48*60*60);
1.869     albertel 10172: 
1.847     albertel 10173: 	return %iphost;
1.598     albertel 10174:     }
                   10175: 
1.992     raeburn  10176:     #
                   10177:     #  Given a DNS returns the loncapa host name for that DNS 
                   10178:     # 
                   10179:     sub host_from_dns {
                   10180:         my ($dns) = @_;
                   10181:         my @hosts;
                   10182:         my $ip;
                   10183: 
1.993     raeburn  10184:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10185:             $ip = $name_to_ip{$dns};
                   10186:         }
                   10187:         if (!$ip) {
                   10188:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10189:             if (length($ip) == 4) { 
                   10190: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10191:             }
                   10192:         }
                   10193:         if ($ip) {
                   10194: 	    @hosts = get_hosts_from_ip($ip);
                   10195: 	    return $hosts[0];
                   10196:         }
                   10197:         return undef;
1.986     foxr     10198:     }
1.992     raeburn  10199: 
1.1056.4.3  raeburn  10200:     sub get_internet_names {
                   10201:         my ($lonid) = @_;
                   10202:         return if ($lonid eq '');
                   10203:         my ($idnref,$cached)=
                   10204:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10205:         if ($cached) {
                   10206:             return $idnref;
                   10207:         }
                   10208:         my $ip = &get_host_ip($lonid);
                   10209:         my @hosts = &get_hosts_from_ip($ip);
                   10210:         my %iphost = &get_iphost();
                   10211:         my (@idns,%seen);
                   10212:         foreach my $id (@hosts) {
                   10213:             my $dom = &host_domain($id);
                   10214:             my $prim_id = &domain($dom,'primary');
                   10215:             my $prim_ip = &get_host_ip($prim_id);
                   10216:             next if ($seen{$prim_ip});
                   10217:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10218:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10219:                     my $intdom = &internet_dom($id);
                   10220:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10221:                         push(@idns,$intdom);
                   10222:                     }
                   10223:                 }
                   10224:             }
                   10225:             $seen{$prim_ip} = 1;
                   10226:         }
                   10227:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10228:     }
                   10229: 
                   10230: }
                   10231: 
                   10232: sub all_loncaparevs {
                   10233:     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);
1.986     foxr     10234: }
                   10235: 
1.862     albertel 10236: BEGIN {
                   10237: 
                   10238: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10239:     unless ($readit) {
                   10240: {
                   10241:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10242:     %perlvar = (%perlvar,%{$configvars});
                   10243: }
                   10244: 
                   10245: 
1.1       albertel 10246: # ------------------------------------------------------ Read spare server file
                   10247: {
1.448     albertel 10248:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10249: 
                   10250:     while (my $configline=<$config>) {
                   10251:        chomp($configline);
1.284     matthew  10252:        if ($configline) {
1.784     albertel 10253: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10254: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10255: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10256:        }
                   10257:     }
1.448     albertel 10258:     close($config);
1.1       albertel 10259: }
1.11      www      10260: # ------------------------------------------------------------ Read permissions
                   10261: {
1.448     albertel 10262:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10263: 
                   10264:     while (my $configline=<$config>) {
1.448     albertel 10265: 	chomp($configline);
                   10266: 	if ($configline) {
                   10267: 	    my ($role,$perm)=split(/ /,$configline);
                   10268: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10269: 	}
1.11      www      10270:     }
1.448     albertel 10271:     close($config);
1.11      www      10272: }
                   10273: 
                   10274: # -------------------------------------------- Read plain texts for permissions
                   10275: {
1.448     albertel 10276:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10277: 
                   10278:     while (my $configline=<$config>) {
1.448     albertel 10279: 	chomp($configline);
                   10280: 	if ($configline) {
1.742     raeburn  10281: 	    my ($short,@plain)=split(/:/,$configline);
                   10282:             %{$prp{$short}} = ();
                   10283: 	    if (@plain > 0) {
                   10284:                 $prp{$short}{'std'} = $plain[0];
                   10285:                 for (my $i=1; $i<@plain; $i++) {
                   10286:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10287:                 }
                   10288:             }
1.448     albertel 10289: 	}
1.135     www      10290:     }
1.448     albertel 10291:     close($config);
1.135     www      10292: }
                   10293: 
                   10294: # ---------------------------------------------------------- Read package table
                   10295: {
1.448     albertel 10296:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10297: 
                   10298:     while (my $configline=<$config>) {
1.483     albertel 10299: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10300: 	chomp($configline);
                   10301: 	my ($short,$plain)=split(/:/,$configline);
                   10302: 	my ($pack,$name)=split(/\&/,$short);
                   10303: 	if ($plain ne '') {
                   10304: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10305: 	    $packagetab{$short}=$plain; 
                   10306: 	}
1.11      www      10307:     }
1.448     albertel 10308:     close($config);
1.329     matthew  10309: }
                   10310: 
1.1056.4.3  raeburn  10311: # ---------------------------------------------------------- Read loncaparev table
                   10312: {
                   10313:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10314:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10315:             while (my $configline=<$config>) {
                   10316:                 chomp($configline);
                   10317:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10318:                 $loncaparevs{$hostid}=$loncaparev;
                   10319:             }
                   10320:             close($config);
                   10321:         }
                   10322:     }
                   10323: }
                   10324: 
                   10325: # ---------------------------------------------------------- Read serverhostID table
                   10326: {
                   10327:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10328:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10329:             while (my $configline=<$config>) {
                   10330:                 chomp($configline);
                   10331:                 my ($name,$id)=split(/:/,$configline);
                   10332:                 $serverhomeIDs{$name}=$id;
                   10333:             }
                   10334:             close($config);
                   10335:         }
                   10336:     }
                   10337: }
                   10338: 
1.1056.4.5  raeburn  10339: {
                   10340:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10341:     if (-e $file) {
                   10342:         my $parser = HTML::LCParser->new($file);
                   10343:         while (my $token = $parser->get_token()) {
                   10344:             if ($token->[0] eq 'S') {
                   10345:                 my $item = $token->[1];
                   10346:                 my $name = $token->[2]{'name'};
                   10347:                 my $value = $token->[2]{'value'};
                   10348:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10349:                     my $release = $parser->get_text();
                   10350:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10351:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10352:                 }
                   10353:             }
                   10354:         }
                   10355:     }
                   10356: }
                   10357: 
1.329     matthew  10358: # ------------- set up temporary directory
                   10359: {
                   10360:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10361: 
1.11      www      10362: }
                   10363: 
1.794     albertel 10364: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10365: 				'compress_threshold'=> 20_000,
                   10366:  			        });
1.185     www      10367: 
1.281     www      10368: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10369: $dumpcount=0;
1.958     www      10370: $locknum=0;
1.22      www      10371: 
1.163     harris41 10372: &logtouch();
1.672     albertel 10373: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10374: $readit=1;
1.564     albertel 10375:     {
                   10376: 	use integer;
                   10377: 	my $test=(2**32)+1;
1.568     albertel 10378: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10379: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10380:     }
1.195     www      10381: }
1.1       albertel 10382: }
1.179     www      10383: 
1.1       albertel 10384: 1;
1.191     harris41 10385: __END__
                   10386: 
1.243     albertel 10387: =pod
                   10388: 
1.191     harris41 10389: =head1 NAME
                   10390: 
1.243     albertel 10391: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10392: 
                   10393: =head1 SYNOPSIS
                   10394: 
1.243     albertel 10395: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10396: 
                   10397:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10398: 
1.243     albertel 10399: Common parameters:
                   10400: 
                   10401: =over 4
                   10402: 
                   10403: =item *
                   10404: 
                   10405: $uname : an internal username (if $cname expecting a course Id specifically)
                   10406: 
                   10407: =item *
                   10408: 
                   10409: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10410: 
                   10411: =item *
                   10412: 
                   10413: $symb : a resource instance identifier
                   10414: 
                   10415: =item *
                   10416: 
                   10417: $namespace : the name of a .db file that contains the data needed or
                   10418: being set.
                   10419: 
                   10420: =back
                   10421: 
1.394     bowersj2 10422: =head1 OVERVIEW
1.191     harris41 10423: 
1.394     bowersj2 10424: lonnet provides subroutines which interact with the
                   10425: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10426: about classes, users, and resources.
1.243     albertel 10427: 
                   10428: For many of these objects you can also use this to store data about
                   10429: them or modify them in various ways.
1.191     harris41 10430: 
1.394     bowersj2 10431: =head2 Symbs
1.191     harris41 10432: 
1.394     bowersj2 10433: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10434: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10435: map, the resource number of the resource in the map, and the URL of
                   10436: the resource itself. The latter is somewhat redundant, but might help
                   10437: if maps change.
                   10438: 
                   10439: An example is
                   10440: 
                   10441:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10442: 
                   10443: The respective map entry is
                   10444: 
                   10445:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10446:   title="Problem 2">
                   10447:  </resource>
                   10448: 
                   10449: Symbs are used by the random number generator, as well as to store and
                   10450: restore data specific to a certain instance of for example a problem.
                   10451: 
                   10452: =head2 Storing And Retrieving Data
                   10453: 
                   10454: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10455: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10456: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10457: is is the non-critical message twin of cstore. These functions are for
                   10458: handlers to store a perl hash to a user's permanent data space in an
                   10459: easy manner, and to retrieve it again on another call. It is expected
                   10460: that a handler would use this once at the beginning to retrieve data,
                   10461: and then again once at the end to send only the new data back.
                   10462: 
                   10463: The data is stored in the user's data directory on the user's
                   10464: homeserver under the ID of the course.
                   10465: 
                   10466: The hash that is returned by restore will have all of the previous
                   10467: value for all of the elements of the hash.
                   10468: 
                   10469: Example:
                   10470: 
                   10471:  #creating a hash
                   10472:  my %hash;
                   10473:  $hash{'foo'}='bar';
                   10474: 
                   10475:  #storing it
                   10476:  &Apache::lonnet::cstore(\%hash);
                   10477: 
                   10478:  #changing a value
                   10479:  $hash{'foo'}='notbar';
                   10480: 
                   10481:  #adding a new value
                   10482:  $hash{'bar'}='foo';
                   10483:  &Apache::lonnet::cstore(\%hash);
                   10484: 
                   10485:  #retrieving the hash
                   10486:  my %history=&Apache::lonnet::restore();
                   10487: 
                   10488:  #print the hash
                   10489:  foreach my $key (sort(keys(%history))) {
                   10490:    print("\%history{$key} = $history{$key}");
                   10491:  }
                   10492: 
                   10493: Will print out:
1.191     harris41 10494: 
1.394     bowersj2 10495:  %history{1:foo} = bar
                   10496:  %history{1:keys} = foo:timestamp
                   10497:  %history{1:timestamp} = 990455579
                   10498:  %history{2:bar} = foo
                   10499:  %history{2:foo} = notbar
                   10500:  %history{2:keys} = foo:bar:timestamp
                   10501:  %history{2:timestamp} = 990455580
                   10502:  %history{bar} = foo
                   10503:  %history{foo} = notbar
                   10504:  %history{timestamp} = 990455580
                   10505:  %history{version} = 2
                   10506: 
                   10507: Note that the special hash entries C<keys>, C<version> and
                   10508: C<timestamp> were added to the hash. C<version> will be equal to the
                   10509: total number of versions of the data that have been stored. The
                   10510: C<timestamp> attribute will be the UNIX time the hash was
                   10511: stored. C<keys> is available in every historical section to list which
                   10512: keys were added or changed at a specific historical revision of a
                   10513: hash.
                   10514: 
                   10515: B<Warning>: do not store the hash that restore returns directly. This
                   10516: will cause a mess since it will restore the historical keys as if the
                   10517: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10518: 
1.394     bowersj2 10519: Calling convention:
1.191     harris41 10520: 
1.394     bowersj2 10521:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10522:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10523: 
1.394     bowersj2 10524: For more detailed information, see lonnet specific documentation.
1.191     harris41 10525: 
1.394     bowersj2 10526: =head1 RETURN MESSAGES
1.191     harris41 10527: 
1.394     bowersj2 10528: =over 4
1.191     harris41 10529: 
1.394     bowersj2 10530: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10531: 
1.394     bowersj2 10532: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10533: when the connection is brought back up
1.191     harris41 10534: 
1.394     bowersj2 10535: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10536: for later delivery
1.191     harris41 10537: 
1.967     bisitz   10538: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10539: 
1.394     bowersj2 10540: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10541: that was requested
1.191     harris41 10542: 
1.243     albertel 10543: =back
1.191     harris41 10544: 
1.243     albertel 10545: =head1 PUBLIC SUBROUTINES
1.191     harris41 10546: 
1.243     albertel 10547: =head2 Session Environment Functions
1.191     harris41 10548: 
1.243     albertel 10549: =over 4
1.191     harris41 10550: 
1.394     bowersj2 10551: =item * 
                   10552: X<appenv()>
1.949     raeburn  10553: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10554: the user envirnoment file, and will be restored for each access this
1.620     albertel 10555: user makes during this session, also modifies the %env for the current
1.949     raeburn  10556: process. Optional rolesarrayref - if defined contains a reference to an array
                   10557: of roles which are exempt from the restriction on modifying user.role entries 
                   10558: in the user's environment.db and in %env.    
1.191     harris41 10559: 
                   10560: =item *
1.394     bowersj2 10561: X<delenv()>
1.987     raeburn  10562: B<delenv($delthis,$regexp)>: removes all items from the session
                   10563: environment file that begin with $delthis. If the 
                   10564: optional second arg - $regexp - is true, $delthis is treated as a 
                   10565: regular expression, otherwise \Q$delthis\E is used. 
                   10566: The values are also deleted from the current processes %env.
1.191     harris41 10567: 
1.795     albertel 10568: =item * get_env_multiple($name) 
                   10569: 
                   10570: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10571: values may be defined and end up as an array ref.
                   10572: 
                   10573: returns an array of values
                   10574: 
1.243     albertel 10575: =back
                   10576: 
                   10577: =head2 User Information
1.191     harris41 10578: 
1.243     albertel 10579: =over 4
1.191     harris41 10580: 
                   10581: =item *
1.394     bowersj2 10582: X<queryauthenticate()>
                   10583: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10584: authentication scheme
                   10585: 
                   10586: =item *
1.394     bowersj2 10587: X<authenticate()>
1.1056.4.3  raeburn  10588: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10589: authenticate user from domain's lib servers (first use the current
                   10590: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10591: $checkdefauth is optional (value is 1 if a check should be made to
                   10592:    authenticate user using default authentication method, and allow
                   10593:    account creation if username does not have account in the domain).
                   10594: $clientcancheckhost is optional (value is 1 if checking whether the
                   10595:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10596: 
                   10597: =item *
1.394     bowersj2 10598: X<homeserver()>
                   10599: B<homeserver($uname,$udom)>: find the server which has
                   10600: the user's directory and files (there must be only one), this caches
                   10601: the answer, and also caches if there is a borken connection.
1.191     harris41 10602: 
                   10603: =item *
1.394     bowersj2 10604: X<idget()>
                   10605: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10606: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10607: username, and only 1 username per ID in a specific domain) (returns
                   10608: hash: id=>name,id=>name)
1.191     harris41 10609: 
                   10610: =item *
1.394     bowersj2 10611: X<idrget()>
                   10612: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10613: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10614: 
                   10615: =item *
1.394     bowersj2 10616: X<idput()>
                   10617: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10618: 
                   10619: =item *
1.394     bowersj2 10620: X<rolesinit()>
                   10621: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10622: 
                   10623: =item *
1.551     albertel 10624: X<getsection()>
                   10625: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10626: course $cname, return section name/number or '' for "not in course"
                   10627: and '-1' for "no section"
                   10628: 
                   10629: =item *
1.394     bowersj2 10630: X<userenvironment()>
                   10631: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10632: passed in @what from the requested user's environment, returns a hash
                   10633: 
1.858     raeburn  10634: =item * 
                   10635: X<userlog_query()>
1.859     albertel 10636: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10637: activity.log file. %filters defines filters applied when parsing the
                   10638: log file. These can be start or end timestamps, or the type of action
                   10639: - log to look for Login or Logout events, check for Checkin or
                   10640: Checkout, role for role selection. The response is in the form
                   10641: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10642: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10643: 
1.243     albertel 10644: =back
                   10645: 
                   10646: =head2 User Roles
                   10647: 
                   10648: =over 4
                   10649: 
                   10650: =item *
                   10651: 
1.810     raeburn  10652: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10653:  F: full access
                   10654:  U,I,K: authentication modes (cxx only)
                   10655:  '': forbidden
                   10656:  1: user needs to choose course
                   10657:  2: browse allowed
1.766     albertel 10658:  A: passphrase authentication needed
1.243     albertel 10659: 
                   10660: =item *
                   10661: 
                   10662: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10663: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10664: and course level
                   10665: 
                   10666: =item *
                   10667: 
1.988     raeburn  10668: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10669: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10670: $type is Course (default) or Community.
1.988     raeburn  10671: If $forcedefault evaluates to true, text returned will be default 
                   10672: text for $type. Otherwise, if this is a course, the text returned 
                   10673: will be a custom name for the role (if defined in the course's 
                   10674: environment).  If no custom name is defined the default is returned.
                   10675:    
1.832     raeburn  10676: =item *
                   10677: 
1.935     raeburn  10678: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10679: All arguments are optional. Returns a hash of a roles, either for
                   10680: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10681: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10682: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10683: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10684: For each key, value is set to colon-separated start and end times for
                   10685: the role.  If no username and domain are specified, will default to
1.934     raeburn  10686: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10687: of role statuses (active, future or previous), roles 
                   10688: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10689: to restrict the list of roles reported. If no array ref is 
                   10690: provided for types, will default to return only active roles.
1.834     albertel 10691: 
1.243     albertel 10692: =back
                   10693: 
                   10694: =head2 User Modification
                   10695: 
                   10696: =over 4
                   10697: 
                   10698: =item *
                   10699: 
1.957     raeburn  10700: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10701: user for the level given by URL.  Optional start and end dates (leave empty
                   10702: string or zero for "no date")
1.191     harris41 10703: 
                   10704: =item *
                   10705: 
1.243     albertel 10706: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10707: change a users, password, possible return values are: ok,
                   10708: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10709: refused
1.191     harris41 10710: 
                   10711: =item *
                   10712: 
1.243     albertel 10713: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10714: 
                   10715: =item *
                   10716: 
1.1056.4.1  raeburn  10717: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10718:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10719: 
                   10720: will update user information (firstname,middlename,lastname,generation,
                   10721: permanentemail), and if forceid is true, student/employee ID also.
                   10722: A user's institutional affiliation(s) can also be updated.
                   10723: User information fields will not be overwritten with empty entries 
                   10724: unless the field is included in the $candelete array reference.
                   10725: This array is included when a single user is modified via "Manage Users",
                   10726: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10727: 
                   10728: =item *
                   10729: 
1.286     matthew  10730: modifystudent
                   10731: 
1.957     raeburn  10732: modify a student's enrollment and identification information.
1.286     matthew  10733: The course id is resolved based on the current users environment.  
                   10734: This means the envoking user must be a course coordinator or otherwise
                   10735: associated with a course.
                   10736: 
1.297     matthew  10737: This call is essentially a wrapper for lonnet::modifyuser and
                   10738: lonnet::modify_student_enrollment
1.286     matthew  10739: 
                   10740: Inputs: 
                   10741: 
                   10742: =over 4
                   10743: 
1.957     raeburn  10744: =item B<$udom> Student's loncapa domain
1.286     matthew  10745: 
1.957     raeburn  10746: =item B<$uname> Student's loncapa login name
1.286     matthew  10747: 
1.964     bisitz   10748: =item B<$uid> Student/Employee ID
1.286     matthew  10749: 
1.957     raeburn  10750: =item B<$umode> Student's authentication mode
1.286     matthew  10751: 
1.957     raeburn  10752: =item B<$upass> Student's password
1.286     matthew  10753: 
1.957     raeburn  10754: =item B<$first> Student's first name
1.286     matthew  10755: 
1.957     raeburn  10756: =item B<$middle> Student's middle name
1.286     matthew  10757: 
1.957     raeburn  10758: =item B<$last> Student's last name
1.286     matthew  10759: 
1.957     raeburn  10760: =item B<$gene> Student's generation
1.286     matthew  10761: 
1.957     raeburn  10762: =item B<$usec> Student's section in course
1.286     matthew  10763: 
                   10764: =item B<$end> Unix time of the roles expiration
                   10765: 
                   10766: =item B<$start> Unix time of the roles start date
                   10767: 
                   10768: =item B<$forceid> If defined, allow $uid to be changed
                   10769: 
                   10770: =item B<$desiredhome> server to use as home server for student
                   10771: 
1.957     raeburn  10772: =item B<$email> Student's permanent e-mail address
                   10773: 
                   10774: =item B<$type> Type of enrollment (auto or manual)
                   10775: 
1.963     raeburn  10776: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10777: 
                   10778: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10779: 
1.963     raeburn  10780: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10781: 
1.963     raeburn  10782: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10783: 
1.963     raeburn  10784: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10785: 
1.286     matthew  10786: =back
1.297     matthew  10787: 
                   10788: =item *
                   10789: 
                   10790: modify_student_enrollment
                   10791: 
                   10792: Change a students enrollment status in a class.  The environment variable
                   10793: 'role.request.course' must be defined for this function to proceed.
                   10794: 
                   10795: Inputs:
                   10796: 
                   10797: =over 4
                   10798: 
                   10799: =item $udom, students domain
                   10800: 
                   10801: =item $uname, students name
                   10802: 
                   10803: =item $uid, students user id
                   10804: 
                   10805: =item $first, students first name
                   10806: 
                   10807: =item $middle
                   10808: 
                   10809: =item $last
                   10810: 
                   10811: =item $gene
                   10812: 
                   10813: =item $usec
                   10814: 
                   10815: =item $end
                   10816: 
                   10817: =item $start
                   10818: 
1.957     raeburn  10819: =item $type
                   10820: 
                   10821: =item $locktype
                   10822: 
                   10823: =item $cid
                   10824: 
                   10825: =item $selfenroll
                   10826: 
                   10827: =item $context
                   10828: 
1.297     matthew  10829: =back
                   10830: 
1.191     harris41 10831: 
                   10832: =item *
                   10833: 
1.243     albertel 10834: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10835: custom role; give a custom role to a user for the level given by URL.  Specify
                   10836: name and domain of role author, and role name
1.191     harris41 10837: 
                   10838: =item *
                   10839: 
1.243     albertel 10840: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10841: 
                   10842: =item *
                   10843: 
1.243     albertel 10844: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10845: 
                   10846: =back
                   10847: 
                   10848: =head2 Course Infomation
                   10849: 
                   10850: =over 4
1.191     harris41 10851: 
                   10852: =item *
                   10853: 
1.631     albertel 10854: coursedescription($courseid) : returns a hash of information about the
                   10855: specified course id, including all environment settings for the
                   10856: course, the description of the course will be in the hash under the
                   10857: key 'description'
1.191     harris41 10858: 
                   10859: =item *
                   10860: 
1.624     albertel 10861: resdata($name,$domain,$type,@which) : request for current parameter
                   10862: setting for a specific $type, where $type is either 'course' or 'user',
                   10863: @what should be a list of parameters to ask about. This routine caches
                   10864: answers for 5 minutes.
1.243     albertel 10865: 
1.877     foxr     10866: =item *
                   10867: 
                   10868: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10869: data base, returning a hash that is keyed by the resource name and has
                   10870: values that are the resource value.  I believe that the timestamps and
                   10871: versions are also returned.
                   10872: 
                   10873: 
1.243     albertel 10874: =back
                   10875: 
                   10876: =head2 Course Modification
                   10877: 
                   10878: =over 4
1.191     harris41 10879: 
                   10880: =item *
                   10881: 
1.243     albertel 10882: writecoursepref($courseid,%prefs) : write preferences (environment
                   10883: database) for a course
1.191     harris41 10884: 
                   10885: =item *
                   10886: 
1.1011    raeburn  10887: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10888: 
                   10889: =item *
                   10890: 
1.1038    raeburn  10891: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10892: 
                   10893: =back
                   10894: 
                   10895: =head2 Resource Subroutines
                   10896: 
                   10897: =over 4
1.191     harris41 10898: 
                   10899: =item *
                   10900: 
1.243     albertel 10901: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10902: 
                   10903: =item *
                   10904: 
1.243     albertel 10905: repcopy($filename) : subscribes to the requested file, and attempts to
                   10906: replicate from the owning library server, Might return
1.607     raeburn  10907: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10908: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10909: resource. Expects the local filesystem pathname
                   10910: (/home/httpd/html/res/....)
                   10911: 
                   10912: =back
                   10913: 
                   10914: =head2 Resource Information
                   10915: 
                   10916: =over 4
1.191     harris41 10917: 
                   10918: =item *
                   10919: 
1.243     albertel 10920: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10921: a vairety of different possible values, $varname should be a request
                   10922: string, and the other parameters can be used to specify who and what
                   10923: one is asking about.
                   10924: 
                   10925: Possible values for $varname are environment.lastname (or other item
                   10926: from the envirnment hash), user.name (or someother aspect about the
                   10927: user), resource.0.maxtries (or some other part and parameter of a
                   10928: resource)
1.204     albertel 10929: 
                   10930: =item *
                   10931: 
1.243     albertel 10932: directcondval($number) : get current value of a condition; reads from a state
                   10933: string
1.204     albertel 10934: 
                   10935: =item *
                   10936: 
1.243     albertel 10937: condval($condidx) : value of condition index based on state
1.204     albertel 10938: 
                   10939: =item *
                   10940: 
1.243     albertel 10941: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10942: resource's metadata, $what should be either a specific key, or either
                   10943: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10944: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10945: 
                   10946: this function automatically caches all requests
1.191     harris41 10947: 
                   10948: =item *
                   10949: 
1.243     albertel 10950: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10951: network of library servers; returns file handle of where SQL and regex results
                   10952: will be stored for query
1.191     harris41 10953: 
                   10954: =item *
                   10955: 
1.243     albertel 10956: symbread($filename) : return symbolic list entry (filename argument optional);
                   10957: returns the data handle
1.191     harris41 10958: 
                   10959: =item *
                   10960: 
1.243     albertel 10961: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10962: a possible symb for the URL in $thisfn, and if is an encryypted
                   10963: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10964: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10965: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10966: 
1.191     harris41 10967: 
                   10968: =item *
                   10969: 
1.243     albertel 10970: symbclean($symb) : removes versions numbers from a symb, returns the
                   10971: cleaned symb
1.191     harris41 10972: 
                   10973: =item *
                   10974: 
1.243     albertel 10975: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10976: course map, user must be in a course for it to work.
1.191     harris41 10977: 
                   10978: =item *
                   10979: 
1.243     albertel 10980: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10981: 
                   10982: =item *
                   10983: 
1.243     albertel 10984: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10985: a random seed, all arguments are optional, if they aren't sent it uses the
                   10986: environment to derive them. Note: if symb isn't sent and it can't get one
                   10987: from &symbread it will use the current time as its return value
1.191     harris41 10988: 
                   10989: =item *
                   10990: 
1.243     albertel 10991: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10992: unfakeable, receipt
1.191     harris41 10993: 
                   10994: =item *
                   10995: 
1.620     albertel 10996: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10997: 
                   10998: =item *
                   10999: 
1.243     albertel 11000: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11001: 
                   11002: =item *
                   11003: 
1.243     albertel 11004: 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 11005: 
                   11006: =item *
                   11007: 
1.243     albertel 11008: 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 11009: 
                   11010: =item *
                   11011: 
1.243     albertel 11012: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11013: 
                   11014: =item *
                   11015: 
1.243     albertel 11016: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11017: forcing spreadsheet to reevaluate the resource scores next time.
                   11018: 
                   11019: =back
                   11020: 
                   11021: =head2 Storing/Retreiving Data
                   11022: 
                   11023: =over 4
1.191     harris41 11024: 
                   11025: =item *
                   11026: 
1.243     albertel 11027: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11028: for this url; hashref needs to be given and should be a \%hashname; the
                   11029: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11030: be derived from the env
1.191     harris41 11031: 
                   11032: =item *
                   11033: 
1.243     albertel 11034: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11035: uses critical subroutine
1.191     harris41 11036: 
                   11037: =item *
                   11038: 
1.243     albertel 11039: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11040: all args are optional
1.191     harris41 11041: 
                   11042: =item *
                   11043: 
1.717     albertel 11044: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11045: dumps the complete (or key matching regexp) namespace into a hash
                   11046: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11047: normally &store()ed into
                   11048: 
                   11049: $range should be either an integer '100' (give me the first 100
                   11050:                                            matching records)
                   11051:               or be  two integers sperated by a - with no spaces
                   11052:                  '30-50' (give me the 30th through the 50th matching
                   11053:                           records)
                   11054: 
                   11055: 
                   11056: =item *
                   11057: 
                   11058: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11059: replaces a &store() version of data with a replacement set of data
                   11060: for a particular resource in a namespace passed in the $storehash hash 
                   11061: reference
                   11062: 
                   11063: =item *
                   11064: 
1.243     albertel 11065: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11066: works very similar to store/cstore, but all data is stored in a
                   11067: temporary location and can be reset using tmpreset, $storehash should
                   11068: be a hash reference, returns nothing on success
1.191     harris41 11069: 
                   11070: =item *
                   11071: 
1.243     albertel 11072: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11073: similar to restore, but all data is stored in a temporary location and
                   11074: can be reset using tmpreset. Returns a hash of values on success,
                   11075: error string otherwise.
1.191     harris41 11076: 
                   11077: =item *
                   11078: 
1.243     albertel 11079: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11080: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11081: 
                   11082: =item *
                   11083: 
1.243     albertel 11084: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11085: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11086: 
                   11087: =item *
                   11088: 
1.243     albertel 11089: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11090: namesp ($udom and $uname are optional)
1.191     harris41 11091: 
                   11092: =item *
                   11093: 
1.702     albertel 11094: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11095: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11096: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11097: 
1.702     albertel 11098: $range should be either an integer '100' (give me the first 100
                   11099:                                            matching records)
                   11100:               or be  two integers sperated by a - with no spaces
                   11101:                  '30-50' (give me the 30th through the 50th matching
                   11102:                           records)
1.449     matthew  11103: =item *
                   11104: 
                   11105: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11106: $store can be a scalar, an array reference, or if the amount to be 
                   11107: incremented is > 1, a hash reference.
                   11108: 
                   11109: ($udom and $uname are optional)
1.191     harris41 11110: 
                   11111: =item *
                   11112: 
1.243     albertel 11113: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11114: ($udom and $uname are optional)
1.191     harris41 11115: 
                   11116: =item *
                   11117: 
1.243     albertel 11118: cput($namespace,$storehash,$udom,$uname) : critical put
                   11119: ($udom and $uname are optional)
1.191     harris41 11120: 
                   11121: =item *
                   11122: 
1.748     albertel 11123: newput($namespace,$storehash,$udom,$uname) :
                   11124: 
                   11125: Attempts to store the items in the $storehash, but only if they don't
                   11126: currently exist, if this succeeds you can be certain that you have 
                   11127: successfully created a new key value pair in the $namespace db.
                   11128: 
                   11129: 
                   11130: Args:
                   11131:  $namespace: name of database to store values to
                   11132:  $storehash: hashref to store to the db
                   11133:  $udom: (optional) domain of user containing the db
                   11134:  $uname: (optional) name of user caontaining the db
                   11135: 
                   11136: Returns:
                   11137:  'ok' -> succeeded in storing all keys of $storehash
                   11138:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11139:                         least <key> already existed in the db (other
                   11140:                         requested keys may also already exist)
1.967     bisitz   11141:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11142:  'con_lost' -> unable to contact request server
                   11143:  'refused' -> action was not allowed by remote machine
                   11144: 
                   11145: 
                   11146: =item *
                   11147: 
1.243     albertel 11148: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11149: reference filled in from namesp (encrypts the return communication)
                   11150: ($udom and $uname are optional)
1.191     harris41 11151: 
                   11152: =item *
                   11153: 
1.243     albertel 11154: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11155: critical subroutine
                   11156: 
1.806     raeburn  11157: =item *
                   11158: 
1.860     raeburn  11159: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11160: array reference filled in from namespace found in domain level on either
                   11161: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11162: 
                   11163: =item *
                   11164: 
1.860     raeburn  11165: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11166: domain level either on specified domain server ($uhome) or primary domain 
                   11167: server ($udom and $uhome are optional)
1.806     raeburn  11168: 
1.943     raeburn  11169: =item * 
                   11170: 
                   11171: get_domain_defaults($target_domain) : returns hash with defaults for
                   11172: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11173: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11174: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11175: Values are retrieved from cache (if current), or from domain's configuration.db
                   11176: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11177: or lonTabs/domain.tab. 
                   11178: 
                   11179: %domdefaults = &get_auth_defaults($target_domain);
                   11180: 
1.243     albertel 11181: =back
                   11182: 
                   11183: =head2 Network Status Functions
                   11184: 
                   11185: =over 4
1.191     harris41 11186: 
                   11187: =item *
                   11188: 
                   11189: dirlist($uri) : return directory list based on URI
                   11190: 
                   11191: =item *
                   11192: 
1.243     albertel 11193: spareserver() : find server with least workload from spare.tab
                   11194: 
1.986     foxr     11195: 
                   11196: =item *
                   11197: 
                   11198: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11199: if there is no corresponding loncapa host.
                   11200: 
1.243     albertel 11201: =back
                   11202: 
1.986     foxr     11203: 
1.243     albertel 11204: =head2 Apache Request
                   11205: 
                   11206: =over 4
1.191     harris41 11207: 
                   11208: =item *
                   11209: 
1.243     albertel 11210: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11211: localhost, posts hash
                   11212: 
                   11213: =back
                   11214: 
                   11215: =head2 Data to String to Data
                   11216: 
                   11217: =over 4
1.191     harris41 11218: 
                   11219: =item *
                   11220: 
1.243     albertel 11221: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11222: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11223: 
                   11224: =item *
                   11225: 
1.243     albertel 11226: hashref2str($hashref) : convert a hashref into a string complete with
                   11227: escaping and '=' and '&' separators, supports elements that are
                   11228: arrayrefs and hashrefs
1.191     harris41 11229: 
                   11230: =item *
                   11231: 
1.243     albertel 11232: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11233: with escaping and '&' separators, supports elements that are arrayrefs
                   11234: and hashrefs
1.191     harris41 11235: 
                   11236: =item *
                   11237: 
1.243     albertel 11238: str2hash($string) : convert string to hash using unescaping and
                   11239: splitting on '=' and '&', supports elements that are arrayrefs and
                   11240: hashrefs
1.191     harris41 11241: 
                   11242: =item *
                   11243: 
1.243     albertel 11244: str2array($string) : convert string to hash using unescaping and
                   11245: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11246: 
                   11247: =back
                   11248: 
                   11249: =head2 Logging Routines
                   11250: 
                   11251: =over 4
                   11252: 
                   11253: These routines allow one to make log messages in the lonnet.log and
                   11254: lonnet.perm logfiles.
1.191     harris41 11255: 
                   11256: =item *
                   11257: 
1.243     albertel 11258: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11259: 
                   11260: =item *
                   11261: 
1.243     albertel 11262: logthis() : append message to the normal lonnet.log file, it gets
                   11263: preiodically rolled over and deleted.
1.191     harris41 11264: 
                   11265: =item *
                   11266: 
1.243     albertel 11267: logperm() : append a permanent message to lonnet.perm.log, this log
                   11268: file never gets deleted by any automated portion of the system, only
                   11269: messages of critical importance should go in here.
                   11270: 
                   11271: =back
                   11272: 
                   11273: =head2 General File Helper Routines
                   11274: 
                   11275: =over 4
1.191     harris41 11276: 
                   11277: =item *
                   11278: 
1.481     raeburn  11279: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11280: (a) files in /uploaded
                   11281:   (i) If a local copy of the file exists - 
                   11282:       compares modification date of local copy with last-modified date for 
                   11283:       definitive version stored on home server for course. If local copy is 
                   11284:       stale, requests a new version from the home server and stores it. 
                   11285:       If the original has been removed from the home server, then local copy 
                   11286:       is unlinked.
                   11287:   (ii) If local copy does not exist -
                   11288:       requests the file from the home server and stores it. 
                   11289:   
                   11290:   If $caller is 'uploadrep':  
                   11291:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11292:     for request for files originally uploaded via DOCS. 
                   11293:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11294:   
                   11295:   Otherwise:
                   11296:      This indicates a call from the content generation phase of the request.
                   11297:      -  returns the entire contents of the file or -1.
                   11298:      
                   11299: (b) files in /res
                   11300:    - returns the entire contents of a file or -1; 
                   11301:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11302: 
1.712     albertel 11303: 
                   11304: =item *
                   11305: 
                   11306: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11307:                   reference
                   11308: 
                   11309: returns either a stat() list of data about the file or an empty list
                   11310: if the file doesn't exist or couldn't find out about it (connection
                   11311: problems or user unknown)
                   11312: 
1.191     harris41 11313: =item *
                   11314: 
1.243     albertel 11315: filelocation($dir,$file) : returns file system location of a file
                   11316: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11317: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11318: and a file of ../bob will become /a/bob)
1.191     harris41 11319: 
                   11320: =item *
                   11321: 
                   11322: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11323: filelocation except for hrefs
                   11324: 
                   11325: =item *
                   11326: 
                   11327: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11328: 
1.243     albertel 11329: =back
                   11330: 
1.608     albertel 11331: =head2 Usererfile file routines (/uploaded*)
                   11332: 
                   11333: =over 4
                   11334: 
                   11335: =item *
                   11336: 
                   11337: userfileupload(): main rotine for putting a file in a user or course's
                   11338:                   filespace, arguments are,
                   11339: 
1.620     albertel 11340:  formname - required - this is the name of the element in $env where the
1.608     albertel 11341:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11342:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11343:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 11344:  coursedoc - if true, store the file in the course of the active role
                   11345:              of the current user
                   11346:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11347:          if undefined, it will be placed in "unknown"
                   11348: 
                   11349:  (This routine calls clean_filename() to remove any dangerous
                   11350:  characters from the filename, and then calls finuserfileupload() to
                   11351:  complete the transaction)
                   11352: 
                   11353:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11354:  and /adm/notfound.html if unsuccessful
                   11355: 
                   11356: =item *
                   11357: 
                   11358: clean_filename(): routine for cleaing a filename up for storage in
                   11359:                  userfile space, argument is:
                   11360: 
                   11361:  filename - proposed filename
                   11362: 
                   11363: returns: the new clean filename
                   11364: 
                   11365: =item *
                   11366: 
                   11367: finishuserfileupload(): routine that creaes and sends the file to
                   11368: userspace, probably shouldn't be called directly
                   11369: 
                   11370:   docuname: username or courseid of destination for the file
                   11371:   docudom: domain of user/course of destination for the file
                   11372:   formname: same as for userfileupload()
                   11373:   fname: filename (inculding subdirectories) for the file
                   11374: 
                   11375:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11376:  and /adm/notfound.html if unsuccessful
                   11377: 
                   11378: =item *
                   11379: 
                   11380: renameuserfile(): renames an existing userfile to a new name
                   11381: 
                   11382:   Args:
                   11383:    docuname: username or courseid of destination for the file
                   11384:    docudom: domain of user/course of destination for the file
                   11385:    old: current file name (including any subdirs under userfiles)
                   11386:    new: desired file name (including any subdirs under userfiles)
                   11387: 
                   11388: =item *
                   11389: 
                   11390: mkdiruserfile(): creates a directory is a userfiles dir
                   11391: 
                   11392:   Args:
                   11393:    docuname: username or courseid of destination for the file
                   11394:    docudom: domain of user/course of destination for the file
                   11395:    dir: dir to create (including any subdirs under userfiles)
                   11396: 
                   11397: =item *
                   11398: 
                   11399: removeuserfile(): removes a file that exists in userfiles
                   11400: 
                   11401:   Args:
                   11402:    docuname: username or courseid of destination for the file
                   11403:    docudom: domain of user/course of destination for the file
                   11404:    fname: filname to delete (including any subdirs under userfiles)
                   11405: 
                   11406: =item *
                   11407: 
                   11408: removeuploadedurl(): convience function for removeuserfile()
                   11409: 
                   11410:   Args:
                   11411:    url:  a full /uploaded/... url to delete
                   11412: 
1.747     albertel 11413: =item * 
                   11414: 
                   11415: get_portfile_permissions():
                   11416:   Args:
                   11417:     domain: domain of user or course contain the portfolio files
                   11418:     user: name of user or num of course contain the portfolio files
                   11419:   Returns:
                   11420:     hashref of a dump of the proper file_permissions.db
                   11421:    
                   11422: 
                   11423: =item * 
                   11424: 
                   11425: get_access_controls():
                   11426: 
                   11427: Args:
                   11428:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11429:   group: (optional) the group you want the files associated with
                   11430:   file: (optional) the file you want access info on
                   11431: 
                   11432: Returns:
1.749     raeburn  11433:     a hash (keys are file names) of hashes containing
                   11434:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11435:         values are XML containing access control settings (see below) 
1.747     albertel 11436: 
                   11437: Internal notes:
                   11438: 
1.749     raeburn  11439:  access controls are stored in file_permissions.db as key=value pairs.
                   11440:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11441:         where scope -> public,guest,course,group,domains or users.
                   11442:               end -> UNIX time for end of access (0 -> no end date)
                   11443:               start -> UNIX time for start of access
                   11444: 
                   11445:     value -> XML description of access control
                   11446:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11447:             <start></start>
                   11448:             <end></end>
                   11449: 
                   11450:             <password></password>  for scope type = guest
                   11451: 
                   11452:             <domain></domain>     for scope type = course or group
                   11453:             <number></number>
                   11454:             <roles id="">
                   11455:              <role></role>
                   11456:              <access></access>
                   11457:              <section></section>
                   11458:              <group></group>
                   11459:             </roles>
                   11460: 
                   11461:             <dom></dom>         for scope type = domains
                   11462: 
                   11463:             <users>             for scope type = users
                   11464:              <user>
                   11465:               <uname></uname>
                   11466:               <udom></udom>
                   11467:              </user>
                   11468:             </users>
                   11469:            </scope> 
                   11470:               
                   11471:  Access data is also aggregated for each file in an additional key=value pair:
                   11472:  key -> path to file/file_name\0accesscontrol 
                   11473:  value -> reference to hash
                   11474:           hash contains key = value pairs
                   11475:           where key = uniqueID:scope_end_start
                   11476:                 value = UNIX time record was last updated
                   11477: 
                   11478:           Used to improve speed of look-ups of access controls for each file.  
                   11479:  
                   11480:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11481: 
                   11482: modify_access_controls():
                   11483: 
                   11484: Modifies access controls for a portfolio file
                   11485: Args
                   11486: 1. file name
                   11487: 2. reference to hash of required changes,
                   11488: 3. domain
                   11489: 4. username
                   11490:   where domain,username are the domain of the portfolio owner 
                   11491:   (either a user or a course) 
                   11492: 
                   11493: Returns:
                   11494: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11495: 2. result of deletions ('ok' or 'error', with error message).
                   11496: 3. reference to hash of any new or updated access controls.
                   11497: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11498:    key = integer (inbound ID)
                   11499:    value = uniqueID  
1.747     albertel 11500: 
1.608     albertel 11501: =back
                   11502: 
1.243     albertel 11503: =head2 HTTP Helper Routines
                   11504: 
                   11505: =over 4
                   11506: 
1.191     harris41 11507: =item *
                   11508: 
                   11509: escape() : unpack non-word characters into CGI-compatible hex codes
                   11510: 
                   11511: =item *
                   11512: 
                   11513: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11514: 
1.243     albertel 11515: =back
                   11516: 
                   11517: =head1 PRIVATE SUBROUTINES
                   11518: 
                   11519: =head2 Underlying communication routines (Shouldn't call)
                   11520: 
                   11521: =over 4
                   11522: 
                   11523: =item *
                   11524: 
                   11525: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11526: 
                   11527: =item *
                   11528: 
                   11529: reply() : uses subreply to send a message to remote machine, logs all failures
                   11530: 
                   11531: =item *
                   11532: 
                   11533: critical() : passes a critical message to another server; if cannot
                   11534: get through then place message in connection buffer directory and
                   11535: returns con_delayed, if incapable of saving message, returns
                   11536: con_failed
                   11537: 
                   11538: =item *
                   11539: 
                   11540: reconlonc() : tries to reconnect lonc client processes.
                   11541: 
                   11542: =back
                   11543: 
                   11544: =head2 Resource Access Logging
                   11545: 
                   11546: =over 4
                   11547: 
                   11548: =item *
                   11549: 
                   11550: flushcourselogs() : flush (save) buffer logs and access logs
                   11551: 
                   11552: =item *
                   11553: 
                   11554: courselog($what) : save message for course in hash
                   11555: 
                   11556: =item *
                   11557: 
                   11558: courseacclog($what) : save message for course using &courselog().  Perform
                   11559: special processing for specific resource types (problems, exams, quizzes, etc).
                   11560: 
1.191     harris41 11561: =item *
                   11562: 
                   11563: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11564: as a PerlChildExitHandler
1.243     albertel 11565: 
                   11566: =back
                   11567: 
                   11568: =head2 Other
                   11569: 
                   11570: =over 4
                   11571: 
                   11572: =item *
                   11573: 
                   11574: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11575: 
                   11576: =back
                   11577: 
                   11578: =cut
1.877     foxr     11579: 

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