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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1116  ! raeburn     4: # $Id: lonnet.pm,v 1.1115 2011/06/12 14:18:12 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1090    raeburn    98: use File::Copy;
1.676     albertel   99: 
1.195     www       100: my $readit;
1.550     foxr      101: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.1106    raeburn   199: sub get_server_distarch {
                    200:     my ($lonhost,$ignore_cache) = @_;
                    201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             return;
                    204:         }
                    205:         my $cachetime = 12*3600;
                    206:         if (!$ignore_cache) {
                    207:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    208:             if (defined($cached)) {
                    209:                 return $distarch;
                    210:             }
                    211:         }
                    212:         my $rep = &reply('serverdistarch',$lonhost);
                    213:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    214:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    215:                 $rep eq '') {
                    216:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    217:         }
                    218:     }
                    219:     return;
                    220: }
                    221: 
1.993     raeburn   222: sub get_server_loncaparev {
1.1073    raeburn   223:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   224:     if (defined($lonhost)) {
                    225:         if (!defined(&hostname($lonhost))) {
                    226:             undef($lonhost);
                    227:         }
                    228:     }
                    229:     if (!defined($lonhost)) {
                    230:         if (defined(&domain($dom,'primary'))) {
                    231:             $lonhost=&domain($dom,'primary');
                    232:             if ($lonhost eq 'no_host') {
                    233:                 undef($lonhost);
                    234:             }
                    235:         }
                    236:     }
                    237:     if (defined($lonhost)) {
1.1073    raeburn   238:         my $cachetime = 12*3600;
                    239:         if (!$ignore_cache) {
                    240:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    241:             if (defined($cached)) {
                    242:                 return $loncaparev;
                    243:             }
                    244:         }
                    245:         my ($answer,$loncaparev);
                    246:         my @ids=&current_machine_ids();
                    247:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    248:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   249:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   250:                 $loncaparev = $1;
                    251:             }
                    252:         } else {
                    253:             $answer = &reply('serverloncaparev',$lonhost);
                    254:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    255:                 if ($caller eq 'loncron') {
                    256:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   257:                     $ua->timeout(4);
1.1073    raeburn   258:                     my $protocol = $protocol{$lonhost};
                    259:                     $protocol = 'http' if ($protocol ne 'https');
                    260:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    261:                     my $request=new HTTP::Request('GET',$url);
                    262:                     my $response=$ua->request($request);
                    263:                     unless ($response->is_error()) {
                    264:                         my $content = $response->content;
1.1081    raeburn   265:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   266:                             $loncaparev = $1;
                    267:                         }
                    268:                     }
                    269:                 } else {
                    270:                     $loncaparev = $loncaparevs{$lonhost};
                    271:                 }
1.1081    raeburn   272:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   273:                 $loncaparev = $1;
                    274:             }
1.993     raeburn   275:         }
1.1073    raeburn   276:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   277:     }
                    278: }
                    279: 
1.1074    raeburn   280: sub get_server_homeID {
                    281:     my ($hostname,$ignore_cache,$caller) = @_;
                    282:     unless ($ignore_cache) {
                    283:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    284:         if (defined($cached)) {
                    285:             return $serverhomeID;
                    286:         }
                    287:     }
                    288:     my $cachetime = 12*3600;
                    289:     my $serverhomeID;
                    290:     if ($caller eq 'loncron') { 
                    291:         my @machine_ids = &machine_ids($hostname);
                    292:         foreach my $id (@machine_ids) {
                    293:             my $response = &reply('serverhomeID',$id);
                    294:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    295:                 $serverhomeID = $response;
                    296:                 last;
                    297:             }
                    298:         }
                    299:         if ($serverhomeID eq '') {
                    300:             $serverhomeID = $machine_ids[-1];
                    301:         }
                    302:     } else {
                    303:         $serverhomeID = $serverhomeIDs{$hostname};
                    304:     }
                    305:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    306: }
                    307: 
1.1       albertel  308: # -------------------------------------------------- Non-critical communication
                    309: sub subreply {
                    310:     my ($cmd,$server)=@_;
1.838     albertel  311:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      312:     #
                    313:     #  With loncnew process trimming, there's a timing hole between lonc server
                    314:     #  process exit and the master server picking up the listen on the AF_UNIX
                    315:     #  socket.  In that time interval, a lock file will exist:
                    316: 
                    317:     my $lockfile=$peerfile.".lock";
                    318:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    319: 	sleep(1);
                    320:     }
                    321:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      322:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      323:     #
1.550     foxr      324:     #   We'll give the connection a few tries before abandoning it.  If
                    325:     #   connection is not possible, we'll con_lost back to the client.
                    326:     #   
                    327:     my $client;
                    328:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    329: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    330: 				      Type    => SOCK_STREAM,
                    331: 				      Timeout => 10);
1.869     albertel  332: 	if ($client) {
1.550     foxr      333: 	    last;		# Connected!
1.850     albertel  334: 	} else {
1.853     albertel  335: 	    &create_connection(&hostname($server),$server);
1.550     foxr      336: 	}
1.850     albertel  337:         sleep(1);		# Try again later if failed connection.
1.550     foxr      338:     }
                    339:     my $answer;
                    340:     if ($client) {
1.704     albertel  341: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      342: 	$answer=<$client>;
                    343: 	if (!$answer) { $answer="con_lost"; }
                    344: 	chomp($answer);
                    345:     } else {
                    346: 	$answer = 'con_lost';	# Failed connection.
                    347:     }
1.1       albertel  348:     return $answer;
                    349: }
                    350: 
                    351: sub reply {
                    352:     my ($cmd,$server)=@_;
1.838     albertel  353:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  354:     my $answer=subreply($cmd,$server);
1.65      www       355:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  356:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       357:                 " $cmd to $server returned $answer</font>");
                    358:     }
1.1       albertel  359:     return $answer;
                    360: }
                    361: 
                    362: # ----------------------------------------------------------- Send USR1 to lonc
                    363: 
                    364: sub reconlonc {
1.891     albertel  365:     my ($lonid) = @_;
                    366:     my $hostname = &hostname($lonid);
                    367:     if ($lonid) {
                    368: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    369: 	if ($hostname && -e $peerfile) {
                    370: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    371: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    372: 					     Type    => SOCK_STREAM,
                    373: 					     Timeout => 10);
                    374: 	    if ($client) {
                    375: 		print $client ("reset_retries\n");
                    376: 		my $answer=<$client>;
                    377: 		#reset just this one.
                    378: 	    }
                    379: 	}
                    380: 	return;
                    381:     }
                    382: 
1.836     www       383:     &logthis("Trying to reconnect lonc");
1.1       albertel  384:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  385:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  386: 	my $loncpid=<$fh>;
                    387:         chomp($loncpid);
                    388:         if (kill 0 => $loncpid) {
                    389: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    390:             kill USR1 => $loncpid;
                    391:             sleep 1;
1.836     www       392:          } else {
1.12      www       393: 	    &logthis(
1.672     albertel  394:                "<font color=\"blue\">WARNING:".
1.12      www       395:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  396:         }
                    397:     } else {
1.836     www       398: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  399:     }
                    400: }
                    401: 
                    402: # ------------------------------------------------------ Critical communication
1.12      www       403: 
1.1       albertel  404: sub critical {
                    405:     my ($cmd,$server)=@_;
1.838     albertel  406:     unless (&hostname($server)) {
1.672     albertel  407:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       408:                " Critical message to unknown server ($server)</font>");
                    409:         return 'no_such_host';
                    410:     }
1.1       albertel  411:     my $answer=reply($cmd,$server);
                    412:     if ($answer eq 'con_lost') {
                    413: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  414: 	my $answer=reply($cmd,$server);
1.1       albertel  415:         if ($answer eq 'con_lost') {
                    416:             my $now=time;
                    417:             my $middlename=$cmd;
1.5       www       418:             $middlename=substr($middlename,0,16);
1.1       albertel  419:             $middlename=~s/\W//g;
                    420:             my $dfilename=
1.305     www       421:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    422:             $dumpcount++;
1.1       albertel  423:             {
1.448     albertel  424: 		my $dfh;
                    425: 		if (open($dfh,">$dfilename")) {
                    426: 		    print $dfh "$cmd\n"; 
                    427: 		    close($dfh);
                    428: 		}
1.1       albertel  429:             }
                    430:             sleep 2;
                    431:             my $wcmd='';
                    432:             {
1.448     albertel  433: 		my $dfh;
                    434: 		if (open($dfh,"<$dfilename")) {
                    435: 		    $wcmd=<$dfh>; 
                    436: 		    close($dfh);
                    437: 		}
1.1       albertel  438:             }
                    439:             chomp($wcmd);
1.7       www       440:             if ($wcmd eq $cmd) {
1.672     albertel  441: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       442:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  443:                 &logperm("D:$server:$cmd");
                    444: 	        return 'con_delayed';
                    445:             } else {
1.672     albertel  446:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       447:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  448:                 &logperm("F:$server:$cmd");
                    449:                 return 'con_failed';
                    450:             }
                    451:         }
                    452:     }
                    453:     return $answer;
1.405     albertel  454: }
                    455: 
1.755     albertel  456: # ------------------------------------------- check if return value is an error
                    457: 
                    458: sub error {
                    459:     my ($result) = @_;
1.756     albertel  460:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  461: 	if ($2 == 2) { return undef; }
                    462: 	return $1;
                    463:     }
                    464:     return undef;
                    465: }
                    466: 
1.783     albertel  467: sub convert_and_load_session_env {
                    468:     my ($lonidsdir,$handle)=@_;
                    469:     my @profile;
                    470:     {
1.917     albertel  471: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    472: 	if (!$opened) {
1.915     albertel  473: 	    return 0;
                    474: 	}
1.783     albertel  475: 	flock($idf,LOCK_SH);
                    476: 	@profile=<$idf>;
                    477: 	close($idf);
                    478:     }
                    479:     my %temp_env;
                    480:     foreach my $line (@profile) {
1.786     albertel  481: 	if ($line !~ m/=/) {
                    482: 	    return 0;
                    483: 	}
1.783     albertel  484: 	chomp($line);
                    485: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    486: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    487:     }
                    488:     unlink("$lonidsdir/$handle.id");
                    489:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    490: 	    0640)) {
                    491: 	%disk_env = %temp_env;
                    492: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    493: 	untie(%disk_env);
                    494:     }
1.786     albertel  495:     return 1;
1.783     albertel  496: }
                    497: 
1.374     www       498: # ------------------------------------------- Transfer profile into environment
1.780     albertel  499: my $env_loaded;
                    500: sub transfer_profile_to_env {
1.788     albertel  501:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    502:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       503: 
1.720     albertel  504:     if (!defined($lonidsdir)) {
                    505: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    506:     }
                    507:     if (!defined($handle)) {
                    508:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    509:     }
                    510: 
1.786     albertel  511:     my $convert;
                    512:     {
1.917     albertel  513:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    514: 	if (!$opened) {
1.915     albertel  515: 	    return;
                    516: 	}
1.786     albertel  517: 	flock($idf,LOCK_SH);
                    518: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    519: 		&GDBM_READER(),0640)) {
                    520: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    521: 	    untie(%disk_env);
                    522: 	} else {
                    523: 	    $convert = 1;
                    524: 	}
                    525:     }
                    526:     if ($convert) {
                    527: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    528: 	    &logthis("Failed to load session, or convert session.");
                    529: 	}
1.374     www       530:     }
1.783     albertel  531: 
1.786     albertel  532:     my %remove;
1.783     albertel  533:     while ( my $envname = each(%env) ) {
1.433     matthew   534:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    535:             if ($time < time-300) {
1.783     albertel  536:                 $remove{$key}++;
1.433     matthew   537:             }
                    538:         }
                    539:     }
1.783     albertel  540: 
1.619     albertel  541:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  542:     $env_loaded=1;
1.783     albertel  543:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   544:         &delenv($expired_key);
1.374     www       545:     }
1.1       albertel  546: }
                    547: 
1.916     albertel  548: # ---------------------------------------------------- Check for valid session 
                    549: sub check_for_valid_session {
                    550:     my ($r) = @_;
                    551:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    552:     my $lonid=$cookies{'lonID'};
                    553:     return undef if (!$lonid);
                    554: 
                    555:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    556:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    557:     return undef if (!-e "$lonidsdir/$handle.id");
                    558: 
1.917     albertel  559:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    560:     return undef if (!$opened);
1.916     albertel  561: 
                    562:     flock($idf,LOCK_SH);
                    563:     my %disk_env;
                    564:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    565: 	    &GDBM_READER(),0640)) {
                    566: 	return undef;	
                    567:     }
                    568: 
                    569:     if (!defined($disk_env{'user.name'})
                    570: 	|| !defined($disk_env{'user.domain'})) {
                    571: 	return undef;
                    572:     }
                    573:     return $handle;
                    574: }
                    575: 
1.830     albertel  576: sub timed_flock {
                    577:     my ($file,$lock_type) = @_;
                    578:     my $failed=0;
                    579:     eval {
                    580: 	local $SIG{__DIE__}='DEFAULT';
                    581: 	local $SIG{ALRM}=sub {
                    582: 	    $failed=1;
                    583: 	    die("failed lock");
                    584: 	};
                    585: 	alarm(13);
                    586: 	flock($file,$lock_type);
                    587: 	alarm(0);
                    588:     };
                    589:     if ($failed) {
                    590: 	return undef;
                    591:     } else {
                    592: 	return 1;
                    593:     }
                    594: }
                    595: 
1.5       www       596: # ---------------------------------------------------------- Append Environment
                    597: 
                    598: sub appenv {
1.949     raeburn   599:     my ($newenv,$roles) = @_;
                    600:     if (ref($newenv) eq 'HASH') {
                    601:         foreach my $key (keys(%{$newenv})) {
                    602:             my $refused = 0;
                    603: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    604:                 $refused = 1;
                    605:                 if (ref($roles) eq 'ARRAY') {
                    606:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    607:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    608:                         $refused = 0;
                    609:                     }
                    610:                 }
                    611:             }
                    612:             if ($refused) {
                    613:                 &logthis("<font color=\"blue\">WARNING: ".
                    614:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    615:                          .'</font>');
                    616: 	        delete($newenv->{$key});
                    617:             } else {
                    618:                 $env{$key}=$newenv->{$key};
                    619:             }
                    620:         }
                    621:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    622:         if ($opened
                    623: 	    && &timed_flock($env_file,LOCK_EX)
                    624: 	    &&
                    625: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    626: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    627: 	    while (my ($key,$value) = each(%{$newenv})) {
                    628: 	        $disk_env{$key} = $value;
                    629: 	    }
                    630: 	    untie(%disk_env);
1.35      www       631:         }
1.191     harris41  632:     }
1.56      www       633:     return 'ok';
                    634: }
                    635: # ----------------------------------------------------- Delete from Environment
                    636: 
                    637: sub delenv {
1.1104    raeburn   638:     my ($delthis,$regexp,$roles) = @_;
                    639:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    640:         my $refused = 1;
                    641:         if (ref($roles) eq 'ARRAY') {
                    642:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    643:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    644:                 $refused = 0;
                    645:             }
                    646:         }
                    647:         if ($refused) {
                    648:             &logthis("<font color=\"blue\">WARNING: ".
                    649:                      "Attempt to delete from environment ".$delthis);
                    650:             return 'error';
                    651:         }
1.56      www       652:     }
1.917     albertel  653:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    654:     if ($opened
1.915     albertel  655: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  656: 	&&
                    657: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    658: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  659: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   660: 	    if ($regexp) {
                    661:                 if ($key=~/^$delthis/) {
                    662:                     delete($env{$key});
                    663:                     delete($disk_env{$key});
                    664:                 } 
                    665:             } else {
                    666:                 if ($key=~/^\Q$delthis\E/) {
                    667: 		    delete($env{$key});
                    668: 		    delete($disk_env{$key});
                    669: 	        }
                    670:             }
1.448     albertel  671: 	}
1.783     albertel  672: 	untie(%disk_env);
1.5       www       673:     }
                    674:     return 'ok';
1.369     albertel  675: }
                    676: 
1.790     albertel  677: sub get_env_multiple {
                    678:     my ($name) = @_;
                    679:     my @values;
                    680:     if (defined($env{$name})) {
                    681:         # exists is it an array
                    682:         if (ref($env{$name})) {
                    683:             @values=@{ $env{$name} };
                    684:         } else {
                    685:             $values[0]=$env{$name};
                    686:         }
                    687:     }
                    688:     return(@values);
                    689: }
                    690: 
1.958     www       691: # ------------------------------------------------------------------- Locking
                    692: 
                    693: sub set_lock {
                    694:     my ($text)=@_;
                    695:     $locknum++;
                    696:     my $id=$$.'-'.$locknum;
                    697:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    698:              'session.lock.'.$id => $text});
                    699:     return $id;
                    700: }
                    701: 
                    702: sub get_locks {
                    703:     my $num=0;
                    704:     my %texts=();
                    705:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    706:        if ($lock=~/\w/) {
                    707:           $num++;
                    708:           $texts{$lock}=$env{'session.lock.'.$lock};
                    709:        }
                    710:    }
                    711:    return ($num,%texts);
                    712: }
                    713: 
                    714: sub remove_lock {
                    715:     my ($id)=@_;
                    716:     my $newlocks='';
                    717:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    718:        if (($lock=~/\w/) && ($lock ne $id)) {
                    719:           $newlocks.=','.$lock;
                    720:        }
                    721:     }
                    722:     &appenv({'session.locks' => $newlocks});
                    723:     &delenv('session.lock.'.$id);
                    724: }
                    725: 
                    726: sub remove_all_locks {
                    727:     my $activelocks=$env{'session.locks'};
                    728:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    729:        if ($lock=~/\w/) {
                    730:           &remove_lock($lock);
                    731:        }
                    732:     }
                    733: }
                    734: 
                    735: 
1.369     albertel  736: # ------------------------------------------ Find out current server userload
                    737: sub userload {
                    738:     my $numusers=0;
                    739:     {
                    740: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    741: 	my $filename;
                    742: 	my $curtime=time;
                    743: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  744: 	    next if ($filename eq '.' || $filename eq '..');
                    745: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  746: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  747: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  748: 	}
                    749: 	closedir(LONIDS);
                    750:     }
                    751:     my $userloadpercent=0;
                    752:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    753:     if ($maxuserload) {
1.371     albertel  754: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  755:     }
1.372     albertel  756:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  757:     return $userloadpercent;
1.283     www       758: }
                    759: 
1.1       albertel  760: # ------------------------------ Find server with least workload from spare.tab
1.11      www       761: 
1.1       albertel  762: sub spareserver {
1.1083    raeburn   763:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  764:     my $spare_server;
1.370     albertel  765:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  766:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    767:                                                      :  $userloadpercent;
1.1083    raeburn   768:     my ($uint_dom,$remotesessions);
                    769:     if (($udom ne '') && (&domain($udom) ne '')) {
                    770:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    771:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    772:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    773:         $remotesessions = $udomdefaults{'remotesessions'};
                    774:     }
1.784     albertel  775:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083    raeburn   776:         if ($uint_dom) {
                    777:              next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    778:                                           $try_server));
                    779:         }
1.784     albertel  780: 	($spare_server, $lowest_load) =
                    781: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    782:     }
                    783: 
                    784:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    785: 
                    786:     if (!$found_server) {
                    787: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1083    raeburn   788:             if ($uint_dom) {
                    789:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    790:                                              $try_server));
                    791:             }
1.784     albertel  792: 	    ($spare_server, $lowest_load) =
                    793: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    794: 	}
                    795:     }
                    796: 
                    797:     if (!$want_server_name) {
1.968     raeburn   798:         my $protocol = 'http';
                    799:         if ($protocol{$spare_server} eq 'https') {
                    800:             $protocol = $protocol{$spare_server};
                    801:         }
1.1001    raeburn   802:         if (defined($spare_server)) {
                    803:             my $hostname = &hostname($spare_server);
1.1083    raeburn   804:             if (defined($hostname)) {
1.1001    raeburn   805: 	        $spare_server = $protocol.'://'.$hostname;
                    806:             }
                    807:         }
1.784     albertel  808:     }
                    809:     return $spare_server;
                    810: }
                    811: 
                    812: sub compare_server_load {
                    813:     my ($try_server, $spare_server, $lowest_load) = @_;
                    814: 
                    815:     my $loadans     = &reply('load',    $try_server);
                    816:     my $userloadans = &reply('userload',$try_server);
                    817: 
                    818:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   819: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  820:     }
                    821: 
                    822:     my $load;
                    823:     if ($loadans =~ /\d/) {
                    824: 	if ($userloadans =~ /\d/) {
                    825: 	    #both are numbers, pick the bigger one
                    826: 	    $load = ($loadans > $userloadans) ? $loadans 
                    827: 		                              : $userloadans;
1.411     albertel  828: 	} else {
1.784     albertel  829: 	    $load = $loadans;
1.411     albertel  830: 	}
1.784     albertel  831:     } else {
                    832: 	$load = $userloadans;
                    833:     }
                    834: 
                    835:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    836: 	$spare_server = $try_server;
                    837: 	$lowest_load  = $load;
1.370     albertel  838:     }
1.784     albertel  839:     return ($spare_server,$lowest_load);
1.202     matthew   840: }
1.914     albertel  841: 
                    842: # --------------------------- ask offload servers if user already has a session
                    843: sub find_existing_session {
                    844:     my ($udom,$uname) = @_;
                    845:     foreach my $try_server (@{ $spareid{'primary'} },
                    846: 			    @{ $spareid{'default'} }) {
                    847: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    848:     }
                    849:     return;
                    850: }
                    851: 
                    852: # -------------------------------- ask if server already has a session for user
                    853: sub has_user_session {
                    854:     my ($lonid,$udom,$uname) = @_;
                    855:     my $result = &reply(join(':','userhassession',
                    856: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    857:     return 1 if ($result eq 'ok');
                    858: 
                    859:     return 0;
                    860: }
                    861: 
1.1076    raeburn   862: # --------- determine least loaded server in a user's domain which allows login
                    863: 
                    864: sub choose_server {
1.1115    raeburn   865:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   866:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   867:     my %servers = &get_servers($udom);
1.1076    raeburn   868:     my $lowest_load = 30000;
1.1116  ! raeburn   869:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   870:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   871:         my $loginvia;
                    872:         if ($checkloginvia) {
                    873:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116  ! raeburn   874:             if ($loginvia) {
        !           875:                 my ($server,$path) = split(/:/,$loginvia);
        !           876:                 ($login_host, $lowest_load) =
        !           877:                     &compare_server_load($server, $login_host, $lowest_load);
        !           878:                 if ($login_host eq $server) {
        !           879:                     $portal_path = $path;
        !           880:                 }
        !           881:             } else {
        !           882:                 ($login_host, $lowest_load) =
        !           883:                     &compare_server_load($lonhost, $login_host, $lowest_load);
        !           884:                 if ($login_host eq $lonhost) {
        !           885:                     $portal_path = '';
        !           886:                 }
        !           887:             }
        !           888:         } else {
1.1076    raeburn   889:             ($login_host, $lowest_load) =
1.1116  ! raeburn   890:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   891:         }
                    892:     }
                    893:     if ($login_host ne '') {
1.1116  ! raeburn   894:         $hostname = &hostname($login_host);
1.1076    raeburn   895:     }
1.1116  ! raeburn   896:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   897: }
                    898: 
1.202     matthew   899: # --------------------------------------------- Try to change a user's password
                    900: 
                    901: sub changepass {
1.799     raeburn   902:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   903:     $currentpass = &escape($currentpass);
                    904:     $newpass     = &escape($newpass);
1.1030    raeburn   905:     my $lonhost = $perlvar{'lonHostID'};
                    906:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   907: 		       $server);
                    908:     if (! $answer) {
                    909: 	&logthis("No reply on password change request to $server ".
                    910: 		 "by $uname in domain $udom.");
                    911:     } elsif ($answer =~ "^ok") {
                    912:         &logthis("$uname in $udom successfully changed their password ".
                    913: 		 "on $server.");
                    914:     } elsif ($answer =~ "^pwchange_failure") {
                    915: 	&logthis("$uname in $udom was unable to change their password ".
                    916: 		 "on $server.  The action was blocked by either lcpasswd ".
                    917: 		 "or pwchange");
                    918:     } elsif ($answer =~ "^non_authorized") {
                    919:         &logthis("$uname in $udom did not get their password correct when ".
                    920: 		 "attempting to change it on $server.");
                    921:     } elsif ($answer =~ "^auth_mode_error") {
                    922:         &logthis("$uname in $udom attempted to change their password despite ".
                    923: 		 "not being locally or internally authenticated on $server.");
                    924:     } elsif ($answer =~ "^unknown_user") {
                    925:         &logthis("$uname in $udom attempted to change their password ".
                    926: 		 "on $server but were unable to because $server is not ".
                    927: 		 "their home server.");
                    928:     } elsif ($answer =~ "^refused") {
                    929: 	&logthis("$server refused to change $uname in $udom password because ".
                    930: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   931:     } elsif ($answer =~ "invalid_client") {
                    932:         &logthis("$server refused to change $uname in $udom password because ".
                    933:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   934:     }
                    935:     return $answer;
1.1       albertel  936: }
                    937: 
1.169     harris41  938: # ----------------------- Try to determine user's current authentication scheme
                    939: 
                    940: sub queryauthenticate {
                    941:     my ($uname,$udom)=@_;
1.456     albertel  942:     my $uhome=&homeserver($uname,$udom);
                    943:     if (!$uhome) {
                    944: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    945: 	return 'no_host';
                    946:     }
                    947:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    948:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    949: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  950:     }
1.456     albertel  951:     return $answer;
1.169     harris41  952: }
                    953: 
1.1       albertel  954: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       955: 
1.1       albertel  956: sub authenticate {
1.1073    raeburn   957:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  958:     $upass=&escape($upass);
                    959:     $uname= &LONCAPA::clean_username($uname);
1.836     www       960:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   961:     my $newhome;
1.836     www       962:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    963: # Maybe the machine was offline and only re-appeared again recently?
                    964:         &reconlonc();
                    965: # One more
1.952     raeburn   966: 	$uhome=&homeserver($uname,$udom,1);
                    967:         if (($uhome eq 'no_host') && $checkdefauth) {
                    968:             if (defined(&domain($udom,'primary'))) {
                    969:                 $newhome=&domain($udom,'primary');
                    970:             }
                    971:             if ($newhome ne '') {
                    972:                 $uhome = $newhome;
                    973:             }
                    974:         }
1.836     www       975: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    976: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   977: 	    return 'no_host';
                    978:         }
1.1       albertel  979:     }
1.1073    raeburn   980:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  981:     if ($answer eq 'authorized') {
1.952     raeburn   982:         if ($newhome) {
                    983:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    984:             return 'no_account_on_host'; 
                    985:         } else {
                    986:             &logthis("User $uname at $udom authorized by $uhome");
                    987:             return $uhome;
                    988:         }
1.471     albertel  989:     }
                    990:     if ($answer eq 'non_authorized') {
                    991: 	&logthis("User $uname at $udom rejected by $uhome");
                    992: 	return 'no_host'; 
1.9       www       993:     }
1.471     albertel  994:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  995:     return 'no_host';
                    996: }
                    997: 
1.1073    raeburn   998: sub can_host_session {
1.1074    raeburn   999:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1000:     my $canhost = 1;
1.1074    raeburn  1001:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1002:     if (ref($remotesessions) eq 'HASH') {
                   1003:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1004:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1005:                 $canhost = 0;
                   1006:             } else {
                   1007:                 $canhost = 1;
                   1008:             }
                   1009:         }
                   1010:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1011:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1012:                 $canhost = 1;
                   1013:             } else {
                   1014:                 $canhost = 0;
                   1015:             }
                   1016:         }
                   1017:         if ($canhost) {
                   1018:             if ($remotesessions->{'version'} ne '') {
                   1019:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1020:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1021:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1022:                         my $major = $1;
                   1023:                         my $minor = $2;
                   1024:                         if (($major < $reqmajor ) ||
                   1025:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1026:                             $canhost = 0;
                   1027:                         }
                   1028:                     } else {
                   1029:                         $canhost = 0;
                   1030:                     }
                   1031:                 }
                   1032:             }
                   1033:         }
                   1034:     }
                   1035:     if ($canhost) {
                   1036:         if (ref($hostedsessions) eq 'HASH') {
                   1037:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1038:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1039:                     $canhost = 0;
                   1040:                 } else {
                   1041:                     $canhost = 1;
                   1042:                 }
                   1043:             }
                   1044:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1045:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1046:                     $canhost = 1;
                   1047:                 } else {
                   1048:                     $canhost = 0;
                   1049:                 }
                   1050:             }
                   1051:         }
                   1052:     }
                   1053:     return $canhost;
                   1054: }
                   1055: 
1.1083    raeburn  1056: sub spare_can_host {
                   1057:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1058:     my $canhost=1;
                   1059:     my @intdoms;
                   1060:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1061:     if (ref($internet_names) eq 'ARRAY') {
                   1062:         @intdoms = @{$internet_names};
                   1063:     }
                   1064:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1065:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1066:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1067:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1068:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1069:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1070:                                      $remotesessions,
                   1071:                                      $defdomdefaults{'hostedsessions'});
                   1072:     }
                   1073:     return $canhost;
                   1074: }
                   1075: 
1.1       albertel 1076: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1077: 
1.599     albertel 1078: my %homecache;
1.1       albertel 1079: sub homeserver {
1.230     stredwic 1080:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1081:     my $index="$uname:$udom";
1.426     albertel 1082: 
1.599     albertel 1083:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1084: 
                   1085:     my %servers = &get_servers($udom,'library');
                   1086:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1087:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1088: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1089: 
                   1090: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1091: 	if ($answer eq 'found') {
                   1092: 	    delete($badServerCache{$tryserver}); 
                   1093: 	    return $homecache{$index}=$tryserver;
                   1094: 	} elsif ($answer eq 'no_host') {
                   1095: 	    $badServerCache{$tryserver}=1;
                   1096: 	}
1.1       albertel 1097:     }    
                   1098:     return 'no_host';
1.70      www      1099: }
                   1100: 
                   1101: # ------------------------------------- Find the usernames behind a list of IDs
                   1102: 
                   1103: sub idget {
                   1104:     my ($udom,@ids)=@_;
                   1105:     my %returnhash=();
                   1106:     
1.841     albertel 1107:     my %servers = &get_servers($udom,'library');
                   1108:     foreach my $tryserver (keys(%servers)) {
                   1109: 	my $idlist=join('&',@ids);
                   1110: 	$idlist=~tr/A-Z/a-z/; 
                   1111: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1112: 	my @answer=();
                   1113: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1114: 	    @answer=split(/\&/,$reply);
                   1115: 	}                    ;
                   1116: 	my $i;
                   1117: 	for ($i=0;$i<=$#ids;$i++) {
                   1118: 	    if ($answer[$i]) {
                   1119: 		$returnhash{$ids[$i]}=$answer[$i];
                   1120: 	    } 
                   1121: 	}
                   1122:     } 
1.70      www      1123:     return %returnhash;
                   1124: }
                   1125: 
                   1126: # ------------------------------------- Find the IDs behind a list of usernames
                   1127: 
                   1128: sub idrget {
                   1129:     my ($udom,@unames)=@_;
                   1130:     my %returnhash=();
1.800     albertel 1131:     foreach my $uname (@unames) {
                   1132:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1133:     }
1.70      www      1134:     return %returnhash;
                   1135: }
                   1136: 
                   1137: # ------------------------------- Store away a list of names and associated IDs
                   1138: 
                   1139: sub idput {
                   1140:     my ($udom,%ids)=@_;
                   1141:     my %servers=();
1.800     albertel 1142:     foreach my $uname (keys(%ids)) {
                   1143: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1144:         my $uhom=&homeserver($uname,$udom);
1.70      www      1145:         if ($uhom ne 'no_host') {
1.800     albertel 1146:             my $id=&escape($ids{$uname});
1.70      www      1147:             $id=~tr/A-Z/a-z/;
1.800     albertel 1148:             my $esc_unam=&escape($uname);
1.70      www      1149: 	    if ($servers{$uhom}) {
1.800     albertel 1150: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1151:             } else {
1.800     albertel 1152:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1153:             }
                   1154:         }
1.191     harris41 1155:     }
1.800     albertel 1156:     foreach my $server (keys(%servers)) {
                   1157:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1158:     }
1.344     www      1159: }
                   1160: 
1.1023    raeburn  1161: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1162: sub dump_dom {
1.1023    raeburn  1163:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1164:     if (!$udom) {
                   1165:         $udom=$env{'user.domain'};
                   1166:     }
                   1167:     my %returnhash;
1.1023    raeburn  1168:     if ($udom) {
                   1169:         my $uname = &get_domainconfiguser($udom);
                   1170:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1171:     }
                   1172:     return %returnhash;
                   1173: }
                   1174: 
1.1023    raeburn  1175: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1176: 
                   1177: sub get_dom {
1.860     raeburn  1178:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1179:     my $items='';
                   1180:     foreach my $item (@$storearr) {
                   1181:         $items.=&escape($item).'&';
                   1182:     }
                   1183:     $items=~s/\&$//;
1.860     raeburn  1184:     if (!$udom) {
                   1185:         $udom=$env{'user.domain'};
                   1186:         if (defined(&domain($udom,'primary'))) {
                   1187:             $uhome=&domain($udom,'primary');
                   1188:         } else {
1.874     albertel 1189:             undef($uhome);
1.860     raeburn  1190:         }
                   1191:     } else {
                   1192:         if (!$uhome) {
                   1193:             if (defined(&domain($udom,'primary'))) {
                   1194:                 $uhome=&domain($udom,'primary');
                   1195:             }
                   1196:         }
                   1197:     }
                   1198:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1199:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1200:         my %returnhash;
1.875     albertel 1201:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1202:             return %returnhash;
                   1203:         }
1.806     raeburn  1204:         my @pairs=split(/\&/,$rep);
                   1205:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1206:             return @pairs;
                   1207:         }
                   1208:         my $i=0;
                   1209:         foreach my $item (@$storearr) {
                   1210:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1211:             $i++;
                   1212:         }
                   1213:         return %returnhash;
                   1214:     } else {
1.880     banghart 1215:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1216:     }
                   1217: }
                   1218: 
                   1219: # -------------------------------------------- put items in domain db files 
                   1220: 
                   1221: sub put_dom {
1.860     raeburn  1222:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1223:     if (!$udom) {
                   1224:         $udom=$env{'user.domain'};
                   1225:         if (defined(&domain($udom,'primary'))) {
                   1226:             $uhome=&domain($udom,'primary');
                   1227:         } else {
1.874     albertel 1228:             undef($uhome);
1.860     raeburn  1229:         }
                   1230:     } else {
                   1231:         if (!$uhome) {
                   1232:             if (defined(&domain($udom,'primary'))) {
                   1233:                 $uhome=&domain($udom,'primary');
                   1234:             }
                   1235:         }
                   1236:     } 
                   1237:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1238:         my $items='';
                   1239:         foreach my $item (keys(%$storehash)) {
                   1240:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1241:         }
                   1242:         $items=~s/\&$//;
                   1243:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1244:     } else {
1.860     raeburn  1245:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1246:     }
                   1247: }
                   1248: 
1.1023    raeburn  1249: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1250: sub newput_dom {
1.1023    raeburn  1251:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1252:     my $result;
                   1253:     if (!$udom) {
                   1254:         $udom=$env{'user.domain'};
                   1255:     }
1.1023    raeburn  1256:     if ($udom) {
                   1257:         my $uname = &get_domainconfiguser($udom);
                   1258:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1259:     }
                   1260:     return $result;
                   1261: }
                   1262: 
1.1023    raeburn  1263: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1264: sub del_dom {
1.1023    raeburn  1265:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1266:     if (ref($storearr) eq 'ARRAY') {
                   1267:         if (!$udom) {
                   1268:             $udom=$env{'user.domain'};
                   1269:         }
1.1023    raeburn  1270:         if ($udom) {
                   1271:             my $uname = &get_domainconfiguser($udom); 
                   1272:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1273:         }
                   1274:     }
                   1275: }
                   1276: 
1.1023    raeburn  1277: # ----------------------------------construct domainconfig user for a domain 
                   1278: sub get_domainconfiguser {
                   1279:     my ($udom) = @_;
                   1280:     return $udom.'-domainconfig';
                   1281: }
                   1282: 
1.837     raeburn  1283: sub retrieve_inst_usertypes {
                   1284:     my ($udom) = @_;
                   1285:     my (%returnhash,@order);
1.989     raeburn  1286:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1287:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1288:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1289:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1290:         @order = @{$domdefs{'inststatusorder'}};
                   1291:     } else {
                   1292:         if (defined(&domain($udom,'primary'))) {
                   1293:             my $uhome=&domain($udom,'primary');
                   1294:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1295:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1296:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1297:                 return (\%returnhash,\@order);
                   1298:             }
                   1299:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1300:             my @pairs=split(/\&/,$hashitems);
                   1301:             foreach my $item (@pairs) {
                   1302:                 my ($key,$value)=split(/=/,$item,2);
                   1303:                 $key = &unescape($key);
                   1304:                 next if ($key =~ /^error: 2 /);
                   1305:                 $returnhash{$key}=&thaw_unescape($value);
                   1306:             }
                   1307:             my @esc_order = split(/\&/,$orderitems);
                   1308:             foreach my $item (@esc_order) {
                   1309:                 push(@order,&unescape($item));
                   1310:             }
                   1311:         } else {
                   1312:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1313:         }
                   1314:     }
                   1315:     return (\%returnhash,\@order);
                   1316: }
                   1317: 
1.868     raeburn  1318: sub is_domainimage {
                   1319:     my ($url) = @_;
                   1320:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1321:         if (&domain($1) ne '') {
                   1322:             return '1';
                   1323:         }
                   1324:     }
                   1325:     return;
                   1326: }
                   1327: 
1.899     raeburn  1328: sub inst_directory_query {
                   1329:     my ($srch) = @_;
                   1330:     my $udom = $srch->{'srchdomain'};
                   1331:     my %results;
                   1332:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1333:     my $outcome;
1.899     raeburn  1334:     if ($homeserver ne '') {
1.904     albertel 1335: 	my $queryid=&reply("querysend:instdirsearch:".
                   1336: 			   &escape($srch->{'srchby'}).':'.
                   1337: 			   &escape($srch->{'srchterm'}).':'.
                   1338: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1339: 	my $host=&hostname($homeserver);
                   1340: 	if ($queryid !~/^\Q$host\E\_/) {
                   1341: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1342: 	    return;
                   1343: 	}
                   1344: 	my $response = &get_query_reply($queryid);
                   1345: 	my $maxtries = 5;
                   1346: 	my $tries = 1;
                   1347: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1348: 	    $response = &get_query_reply($queryid);
                   1349: 	    $tries ++;
                   1350: 	}
                   1351: 
                   1352:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1353:             if ($response eq 'unavailable') {
                   1354:                 $outcome = $response;
                   1355:             } else {
                   1356:                 $outcome = 'ok';
                   1357:                 my @matches = split(/\n/,$response);
                   1358:                 foreach my $match (@matches) {
                   1359:                     my ($key,$value) = split(/=/,$match);
                   1360:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1361:                 }
1.899     raeburn  1362:             }
                   1363:         }
                   1364:     }
1.909     raeburn  1365:     return ($outcome,%results);
1.899     raeburn  1366: }
                   1367: 
                   1368: sub usersearch {
                   1369:     my ($srch) = @_;
                   1370:     my $dom = $srch->{'srchdomain'};
                   1371:     my %results;
                   1372:     my %libserv = &all_library();
                   1373:     my $query = 'usersearch';
                   1374:     foreach my $tryserver (keys(%libserv)) {
                   1375:         if (&host_domain($tryserver) eq $dom) {
                   1376:             my $host=&hostname($tryserver);
                   1377:             my $queryid=
1.911     raeburn  1378:                 &reply("querysend:".&escape($query).':'.
                   1379:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1380:                        &escape($srch->{'srchtype'}).':'.
                   1381:                        &escape($srch->{'srchterm'}),$tryserver);
                   1382:             if ($queryid !~/^\Q$host\E\_/) {
                   1383:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1384:                 next;
1.899     raeburn  1385:             }
                   1386:             my $reply = &get_query_reply($queryid);
                   1387:             my $maxtries = 1;
                   1388:             my $tries = 1;
                   1389:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1390:                 $reply = &get_query_reply($queryid);
                   1391:                 $tries ++;
                   1392:             }
                   1393:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1394:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1395:             } else {
1.911     raeburn  1396:                 my @matches;
                   1397:                 if ($reply =~ /\n/) {
                   1398:                     @matches = split(/\n/,$reply);
                   1399:                 } else {
                   1400:                     @matches = split(/\&/,$reply);
                   1401:                 }
1.899     raeburn  1402:                 foreach my $match (@matches) {
                   1403:                     my ($uname,$udom,%userhash);
1.911     raeburn  1404:                     foreach my $entry (split(/:/,$match)) {
                   1405:                         my ($key,$value) =
                   1406:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1407:                         $userhash{$key} = $value;
                   1408:                         if ($key eq 'username') {
                   1409:                             $uname = $value;
                   1410:                         } elsif ($key eq 'domain') {
                   1411:                             $udom = $value;
1.911     raeburn  1412:                         }
1.899     raeburn  1413:                     }
                   1414:                     $results{$uname.':'.$udom} = \%userhash;
                   1415:                 }
                   1416:             }
                   1417:         }
                   1418:     }
                   1419:     return %results;
                   1420: }
                   1421: 
1.912     raeburn  1422: sub get_instuser {
                   1423:     my ($udom,$uname,$id) = @_;
                   1424:     my $homeserver = &domain($udom,'primary');
                   1425:     my ($outcome,%results);
                   1426:     if ($homeserver ne '') {
                   1427:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1428:                            &escape($id).':'.&escape($udom),$homeserver);
                   1429:         my $host=&hostname($homeserver);
                   1430:         if ($queryid !~/^\Q$host\E\_/) {
                   1431:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1432:             return;
                   1433:         }
                   1434:         my $response = &get_query_reply($queryid);
                   1435:         my $maxtries = 5;
                   1436:         my $tries = 1;
                   1437:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1438:             $response = &get_query_reply($queryid);
                   1439:             $tries ++;
                   1440:         }
                   1441:         if (!&error($response) && $response ne 'refused') {
                   1442:             if ($response eq 'unavailable') {
                   1443:                 $outcome = $response;
                   1444:             } else {
                   1445:                 $outcome = 'ok';
                   1446:                 my @matches = split(/\n/,$response);
                   1447:                 foreach my $match (@matches) {
                   1448:                     my ($key,$value) = split(/=/,$match);
                   1449:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1450:                 }
                   1451:             }
                   1452:         }
                   1453:     }
                   1454:     my %userinfo;
                   1455:     if (ref($results{$uname}) eq 'HASH') {
                   1456:         %userinfo = %{$results{$uname}};
                   1457:     } 
                   1458:     return ($outcome,%userinfo);
                   1459: }
                   1460: 
                   1461: sub inst_rulecheck {
1.923     raeburn  1462:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1463:     my %returnhash;
                   1464:     if ($udom ne '') {
                   1465:         if (ref($rules) eq 'ARRAY') {
                   1466:             @{$rules} = map {&escape($_);} (@{$rules});
                   1467:             my $rulestr = join(':',@{$rules});
                   1468:             my $homeserver=&domain($udom,'primary');
                   1469:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1470:                 my $response;
                   1471:                 if ($item eq 'username') {                
                   1472:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1473:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1474:                                               $homeserver));
1.923     raeburn  1475:                 } elsif ($item eq 'id') {
                   1476:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1477:                                               ':'.&escape($id).':'.$rulestr,
                   1478:                                               $homeserver));
1.945     raeburn  1479:                 } elsif ($item eq 'selfcreate') {
                   1480:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1481:                                                &escape($udom).':'.&escape($uname).
                   1482:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1483:                 }
1.912     raeburn  1484:                 if ($response ne 'refused') {
                   1485:                     my @pairs=split(/\&/,$response);
                   1486:                     foreach my $item (@pairs) {
                   1487:                         my ($key,$value)=split(/=/,$item,2);
                   1488:                         $key = &unescape($key);
                   1489:                         next if ($key =~ /^error: 2 /);
                   1490:                         $returnhash{$key}=&thaw_unescape($value);
                   1491:                     }
                   1492:                 }
                   1493:             }
                   1494:         }
                   1495:     }
                   1496:     return %returnhash;
                   1497: }
                   1498: 
                   1499: sub inst_userrules {
1.923     raeburn  1500:     my ($udom,$check) = @_;
1.912     raeburn  1501:     my (%ruleshash,@ruleorder);
                   1502:     if ($udom ne '') {
                   1503:         my $homeserver=&domain($udom,'primary');
                   1504:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1505:             my $response;
                   1506:             if ($check eq 'id') {
                   1507:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1508:                                  $homeserver);
1.943     raeburn  1509:             } elsif ($check eq 'email') {
                   1510:                 $response=&reply('instemailrules:'.&escape($udom),
                   1511:                                  $homeserver);
1.923     raeburn  1512:             } else {
                   1513:                 $response=&reply('instuserrules:'.&escape($udom),
                   1514:                                  $homeserver);
                   1515:             }
1.912     raeburn  1516:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1517:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1518:                 ($response ne 'no_such_host')) {
                   1519:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1520:                 my @pairs=split(/\&/,$hashitems);
                   1521:                 foreach my $item (@pairs) {
                   1522:                     my ($key,$value)=split(/=/,$item,2);
                   1523:                     $key = &unescape($key);
                   1524:                     next if ($key =~ /^error: 2 /);
                   1525:                     $ruleshash{$key}=&thaw_unescape($value);
                   1526:                 }
                   1527:                 my @esc_order = split(/\&/,$orderitems);
                   1528:                 foreach my $item (@esc_order) {
                   1529:                     push(@ruleorder,&unescape($item));
                   1530:                 }
                   1531:             }
                   1532:         }
                   1533:     }
                   1534:     return (\%ruleshash,\@ruleorder);
                   1535: }
                   1536: 
1.976     raeburn  1537: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1538: 
                   1539: sub get_domain_defaults {
                   1540:     my ($domain) = @_;
                   1541:     my $cachetime = 60*60*24;
                   1542:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1543:     if (defined($cached)) {
                   1544:         if (ref($result) eq 'HASH') {
                   1545:             return %{$result};
                   1546:         }
                   1547:     }
                   1548:     my %domdefaults;
                   1549:     my %domconfig =
1.989     raeburn  1550:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1551:                                   'requestcourses','inststatus',
1.1073    raeburn  1552:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1553:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1554:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1555:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1556:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1557:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1558:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1559:     } else {
                   1560:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1561:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1562:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1563:     }
1.976     raeburn  1564:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1565:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1566:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1567:         } else {
                   1568:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1569:         } 
                   1570:         my @usertools = ('aboutme','blog','portfolio');
                   1571:         foreach my $item (@usertools) {
                   1572:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1573:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1574:             }
                   1575:         }
                   1576:     }
1.985     raeburn  1577:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1578:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1579:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1580:         }
                   1581:     }
1.989     raeburn  1582:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1583:         foreach my $item ('inststatustypes','inststatusorder') {
                   1584:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1585:         }
                   1586:     }
1.1047    raeburn  1587:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1588:         foreach my $item ('canuse_pdfforms') {
                   1589:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1590:         }
                   1591:     }
1.1073    raeburn  1592:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1593:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1594:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1595:         }
                   1596:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1597:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1598:         }
                   1599:     }
1.943     raeburn  1600:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1601:                                   $cachetime);
                   1602:     return %domdefaults;
                   1603: }
                   1604: 
1.344     www      1605: # --------------------------------------------------- Assign a key to a student
                   1606: 
                   1607: sub assign_access_key {
1.364     www      1608: #
                   1609: # a valid key looks like uname:udom#comments
                   1610: # comments are being appended
                   1611: #
1.498     www      1612:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1613:     $kdom=
1.620     albertel 1614:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1615:     $knum=
1.620     albertel 1616:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1617:     $cdom=
1.620     albertel 1618:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1619:     $cnum=
1.620     albertel 1620:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1621:     $udom=$env{'user.name'} unless (defined($udom));
                   1622:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1623:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1624:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1625:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1626:                                                   # assigned to this person
                   1627:                                                   # - this should not happen,
1.345     www      1628:                                                   # unless something went wrong
                   1629:                                                   # the first time around
                   1630: # ready to assign
1.364     www      1631:         $logentry=$1.'; '.$logentry;
1.496     www      1632:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1633:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1634: # key now belongs to user
1.346     www      1635: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1636:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1637:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1638:                 return 'ok';
                   1639:             } else {
                   1640:                 return 
                   1641:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1642: 	    }
                   1643:         } else {
                   1644:             return 'error: Could not assign key, try again later.';
                   1645:         }
1.364     www      1646:     } elsif (!$existing{$ckey}) {
1.345     www      1647: # the key does not exist
                   1648: 	return 'error: The key does not exist';
                   1649:     } else {
                   1650: # the key is somebody else's
                   1651: 	return 'error: The key is already in use';
                   1652:     }
1.344     www      1653: }
                   1654: 
1.364     www      1655: # ------------------------------------------ put an additional comment on a key
                   1656: 
                   1657: sub comment_access_key {
                   1658: #
                   1659: # a valid key looks like uname:udom#comments
                   1660: # comments are being appended
                   1661: #
                   1662:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1663:     $cdom=
1.620     albertel 1664:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1665:     $cnum=
1.620     albertel 1666:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1667:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1668:     if ($existing{$ckey}) {
                   1669:         $existing{$ckey}.='; '.$logentry;
                   1670: # ready to assign
1.367     www      1671:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1672:                                                  $cdom,$cnum) eq 'ok') {
                   1673: 	    return 'ok';
                   1674:         } else {
                   1675: 	    return 'error: Count not store comment.';
                   1676:         }
                   1677:     } else {
                   1678: # the key does not exist
                   1679: 	return 'error: The key does not exist';
                   1680:     }
                   1681: }
                   1682: 
1.344     www      1683: # ------------------------------------------------------ Generate a set of keys
                   1684: 
                   1685: sub generate_access_keys {
1.364     www      1686:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1687:     $cdom=
1.620     albertel 1688:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1689:     $cnum=
1.620     albertel 1690:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1691:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1692:     unless (($cdom) && ($cnum)) { return 0; }
                   1693:     if ($number>10000) { return 0; }
                   1694:     sleep(2); # make sure don't get same seed twice
                   1695:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1696:     my $total=0;
                   1697:     for (my $i=1;$i<=$number;$i++) {
                   1698:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1699:                   sprintf("%lx",int(100000*rand)).'-'.
                   1700:                   sprintf("%lx",int(100000*rand));
                   1701:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1702:        $newkey=~s/0/h/g; # and also 0 and O
                   1703:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1704:        if ($existing{$newkey}) {
                   1705:            $i--;
                   1706:        } else {
1.364     www      1707: 	  if (&put('accesskeys',
                   1708:               { $newkey => '# generated '.localtime().
1.620     albertel 1709:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1710:                            '; '.$logentry },
                   1711: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1712:               $total++;
                   1713: 	  }
                   1714:        }
                   1715:     }
1.620     albertel 1716:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1717:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1718:     return $total;
                   1719: }
                   1720: 
                   1721: # ------------------------------------------------------- Validate an accesskey
                   1722: 
                   1723: sub validate_access_key {
                   1724:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1725:     $cdom=
1.620     albertel 1726:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1727:     $cnum=
1.620     albertel 1728:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1729:     $udom=$env{'user.domain'} unless (defined($udom));
                   1730:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1731:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1732:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1733: }
                   1734: 
                   1735: # ------------------------------------- Find the section of student in a course
1.652     albertel 1736: sub devalidate_getsection_cache {
                   1737:     my ($udom,$unam,$courseid)=@_;
                   1738:     my $hashid="$udom:$unam:$courseid";
                   1739:     &devalidate_cache_new('getsection',$hashid);
                   1740: }
1.298     matthew  1741: 
1.815     albertel 1742: sub courseid_to_courseurl {
                   1743:     my ($courseid) = @_;
                   1744:     #already url style courseid
                   1745:     return $courseid if ($courseid =~ m{^/});
                   1746: 
                   1747:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1748: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1749: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1750: 	return "/$cdom/$cnum";
                   1751:     }
                   1752: 
                   1753:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1754:     if (exists($courseinfo{'num'})) {
                   1755: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1756:     }
                   1757: 
                   1758:     return undef;
                   1759: }
                   1760: 
1.298     matthew  1761: sub getsection {
                   1762:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1763:     my $cachetime=1800;
1.551     albertel 1764: 
                   1765:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1766:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1767:     if (defined($cached)) { return $result; }
                   1768: 
1.298     matthew  1769:     my %Pending; 
                   1770:     my %Expired;
                   1771:     #
                   1772:     # Each role can either have not started yet (pending), be active, 
                   1773:     #    or have expired.
                   1774:     #
                   1775:     # If there is an active role, we are done.
                   1776:     #
                   1777:     # If there is more than one role which has not started yet, 
                   1778:     #     choose the one which will start sooner
                   1779:     # If there is one role which has not started yet, return it.
                   1780:     #
                   1781:     # If there is more than one expired role, choose the one which ended last.
                   1782:     # If there is a role which has expired, return it.
                   1783:     #
1.815     albertel 1784:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  1785:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1786:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1787:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1788:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1789:         my $section=$1;
                   1790:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1791:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1792:         my $now=time;
1.548     albertel 1793:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1794:             $Expired{$end}=$section;
                   1795:             next;
                   1796:         }
1.548     albertel 1797:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1798:             $Pending{$start}=$section;
                   1799:             next;
                   1800:         }
1.599     albertel 1801:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1802:     }
                   1803:     #
                   1804:     # Presumedly there will be few matching roles from the above
                   1805:     # loop and the sorting time will be negligible.
                   1806:     if (scalar(keys(%Pending))) {
                   1807:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1808:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1809:     } 
                   1810:     if (scalar(keys(%Expired))) {
                   1811:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1812:         my $time = pop(@sorted);
1.599     albertel 1813:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1814:     }
1.599     albertel 1815:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1816: }
1.70      www      1817: 
1.599     albertel 1818: sub save_cache {
                   1819:     &purge_remembered();
1.722     albertel 1820:     #&Apache::loncommon::validate_page();
1.620     albertel 1821:     undef(%env);
1.780     albertel 1822:     undef($env_loaded);
1.599     albertel 1823: }
1.452     albertel 1824: 
1.599     albertel 1825: my $to_remember=-1;
                   1826: my %remembered;
                   1827: my %accessed;
                   1828: my $kicks=0;
                   1829: my $hits=0;
1.849     albertel 1830: sub make_key {
                   1831:     my ($name,$id) = @_;
1.872     albertel 1832:     if (length($id) > 65 
                   1833: 	&& length(&escape($id)) > 200) {
                   1834: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1835:     }
1.849     albertel 1836:     return &escape($name.':'.$id);
                   1837: }
                   1838: 
1.599     albertel 1839: sub devalidate_cache_new {
                   1840:     my ($name,$id,$debug) = @_;
                   1841:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1842:     $id=&make_key($name,$id);
1.599     albertel 1843:     $memcache->delete($id);
                   1844:     delete($remembered{$id});
                   1845:     delete($accessed{$id});
                   1846: }
                   1847: 
                   1848: sub is_cached_new {
                   1849:     my ($name,$id,$debug) = @_;
1.849     albertel 1850:     $id=&make_key($name,$id);
1.599     albertel 1851:     if (exists($remembered{$id})) {
                   1852: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1853: 	$accessed{$id}=[&gettimeofday()];
                   1854: 	$hits++;
                   1855: 	return ($remembered{$id},1);
                   1856:     }
                   1857:     my $value = $memcache->get($id);
                   1858:     if (!(defined($value))) {
                   1859: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1860: 	return (undef,undef);
1.416     albertel 1861:     }
1.599     albertel 1862:     if ($value eq '__undef__') {
                   1863: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1864: 	$value=undef;
                   1865:     }
                   1866:     &make_room($id,$value,$debug);
                   1867:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1868:     return ($value,1);
                   1869: }
                   1870: 
                   1871: sub do_cache_new {
                   1872:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1873:     $id=&make_key($name,$id);
1.599     albertel 1874:     my $setvalue=$value;
                   1875:     if (!defined($setvalue)) {
                   1876: 	$setvalue='__undef__';
                   1877:     }
1.623     albertel 1878:     if (!defined($time) ) {
                   1879: 	$time=600;
                   1880:     }
1.599     albertel 1881:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1882:     my $result = $memcache->set($id,$setvalue,$time);
                   1883:     if (! $result) {
1.872     albertel 1884: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1885: 	$memcache->disconnect_all();
1.872     albertel 1886:     }
1.600     albertel 1887:     # need to make a copy of $value
1.919     albertel 1888:     &make_room($id,$value,$debug);
1.599     albertel 1889:     return $value;
                   1890: }
                   1891: 
                   1892: sub make_room {
                   1893:     my ($id,$value,$debug)=@_;
1.919     albertel 1894: 
                   1895:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1896:                                     : $value;
1.599     albertel 1897:     if ($to_remember<0) { return; }
                   1898:     $accessed{$id}=[&gettimeofday()];
                   1899:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1900:     my $to_kick;
                   1901:     my $max_time=0;
                   1902:     foreach my $other (keys(%accessed)) {
                   1903: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1904: 	    $to_kick=$other;
                   1905: 	    $max_time=&tv_interval($accessed{$other});
                   1906: 	}
                   1907:     }
                   1908:     delete($remembered{$to_kick});
                   1909:     delete($accessed{$to_kick});
                   1910:     $kicks++;
                   1911:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1912:     return;
                   1913: }
                   1914: 
1.599     albertel 1915: sub purge_remembered {
1.604     albertel 1916:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1917:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1918:     undef(%remembered);
                   1919:     undef(%accessed);
1.428     albertel 1920: }
1.70      www      1921: # ------------------------------------- Read an entry from a user's environment
                   1922: 
                   1923: sub userenvironment {
                   1924:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1925:     my $items;
                   1926:     foreach my $item (@what) {
                   1927:         $items.=&escape($item).'&';
                   1928:     }
                   1929:     $items=~s/\&$//;
1.70      www      1930:     my %returnhash=();
1.1009    raeburn  1931:     my $uhome = &homeserver($unam,$udom);
                   1932:     unless ($uhome eq 'no_host') {
                   1933:         my @answer=split(/\&/, 
                   1934:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1935:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1936:             return %returnhash;
                   1937:         }
1.1009    raeburn  1938:         my $i;
                   1939:         for ($i=0;$i<=$#what;$i++) {
                   1940: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1941:         }
1.70      www      1942:     }
                   1943:     return %returnhash;
1.1       albertel 1944: }
                   1945: 
1.617     albertel 1946: # ---------------------------------------------------------- Get a studentphoto
                   1947: sub studentphoto {
                   1948:     my ($udom,$unam,$ext) = @_;
                   1949:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1950:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1951:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1952:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1953:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1954:             } else {
                   1955:                 my ($result,$perm_reqd)=
1.707     albertel 1956: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1957:                 if ($result eq 'ok') {
                   1958:                     if (!($perm_reqd eq 'yes')) {
                   1959:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1960:                     }
                   1961:                 }
                   1962:             }
                   1963:         }
                   1964:     } else {
                   1965:         my ($result,$perm_reqd) = 
1.707     albertel 1966: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1967:         if ($result eq 'ok') {
                   1968:             if (!($perm_reqd eq 'yes')) {
                   1969:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1970:             }
                   1971:         }
                   1972:     }
                   1973:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1974: }
                   1975: 
                   1976: sub retrievestudentphoto {
                   1977:     my ($udom,$unam,$ext,$type) = @_;
                   1978:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1979:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1980:     if ($ret eq 'ok') {
                   1981:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1982:         if ($type eq 'thumbnail') {
                   1983:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1984:         }
                   1985:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1986:         return $tokenurl;
                   1987:     } else {
                   1988:         if ($type eq 'thumbnail') {
                   1989:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1990:         } else { 
                   1991:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1992:         }
1.617     albertel 1993:     }
                   1994: }
                   1995: 
1.263     www      1996: # -------------------------------------------------------------------- New chat
                   1997: 
                   1998: sub chatsend {
1.724     raeburn  1999:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2000:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2001:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2002:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2003:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2004: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2005: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2006: }
                   2007: 
                   2008: # ------------------------------------------ Find current version of a resource
                   2009: 
                   2010: sub getversion {
                   2011:     my $fname=&clutter(shift);
                   2012:     unless ($fname=~/^\/res\//) { return -1; }
                   2013:     return &currentversion(&filelocation('',$fname));
                   2014: }
                   2015: 
                   2016: sub currentversion {
                   2017:     my $fname=shift;
                   2018:     my $author=$fname;
                   2019:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2020:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2021:     my $home=&homeserver($uname,$udom);
1.292     www      2022:     if ($home eq 'no_host') { 
                   2023:         return -1; 
                   2024:     }
1.1112    www      2025:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2026:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2027: 	return -1;
                   2028:     }
1.1112    www      2029:     return $answer;
1.263     www      2030: }
                   2031: 
1.1111    www      2032: #
                   2033: # Return special version number of resource if set by override, empty otherwise
                   2034: #
                   2035: sub usedversion {
                   2036:     my $fname=shift;
                   2037:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2038:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2039:     if ($urlversion) { return $urlversion; }
                   2040:     return '';
                   2041: }
                   2042: 
1.1       albertel 2043: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2044: 
1.1       albertel 2045: sub subscribe {
                   2046:     my $fname=shift;
1.761     raeburn  2047:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2048:     $fname=~s/[\n\r]//g;
1.1       albertel 2049:     my $author=$fname;
                   2050:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2051:     my ($udom,$uname)=split(/\//,$author);
                   2052:     my $home=homeserver($uname,$udom);
1.335     albertel 2053:     if ($home eq 'no_host') {
                   2054:         return 'not_found';
1.1       albertel 2055:     }
                   2056:     my $answer=reply("sub:$fname",$home);
1.64      www      2057:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2058: 	$answer.=' by '.$home;
                   2059:     }
1.1       albertel 2060:     return $answer;
                   2061: }
                   2062:     
1.8       www      2063: # -------------------------------------------------------------- Replicate file
                   2064: 
                   2065: sub repcopy {
                   2066:     my $filename=shift;
1.23      www      2067:     $filename=~s/\/+/\//g;
1.607     raeburn  2068:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2069:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2070:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2071: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2072: 	return &repcopy_userfile($filename);
                   2073:     }
1.532     albertel 2074:     $filename=~s/[\n\r]//g;
1.8       www      2075:     my $transname="$filename.in.transfer";
1.828     www      2076: # FIXME: this should flock
1.607     raeburn  2077:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2078:     my $remoteurl=subscribe($filename);
1.64      www      2079:     if ($remoteurl =~ /^con_lost by/) {
                   2080: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2081:            return 'unavailable';
1.8       www      2082:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2083: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2084: 	   return 'not_found';
1.64      www      2085:     } elsif ($remoteurl =~ /^rejected by/) {
                   2086: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2087:            return 'forbidden';
1.20      www      2088:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2089:            return 'ok';
1.8       www      2090:     } else {
1.290     www      2091:         my $author=$filename;
                   2092:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2093:         my ($udom,$uname)=split(/\//,$author);
                   2094:         my $home=homeserver($uname,$udom);
                   2095:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2096:            my @parts=split(/\//,$filename);
                   2097:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2098:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2099:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2100: 	       return 'bad_request';
1.8       www      2101:            }
                   2102:            my $count;
                   2103:            for ($count=5;$count<$#parts;$count++) {
                   2104:                $path.="/$parts[$count]";
                   2105:                if ((-e $path)!=1) {
                   2106: 		   mkdir($path,0777);
                   2107:                }
                   2108:            }
                   2109:            my $ua=new LWP::UserAgent;
                   2110:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2111:            my $response=$ua->request($request,$transname);
                   2112:            if ($response->is_error()) {
                   2113: 	       unlink($transname);
                   2114:                my $message=$response->status_line;
1.672     albertel 2115:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2116:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2117:                return 'unavailable';
1.8       www      2118:            } else {
1.16      www      2119: 	       if ($remoteurl!~/\.meta$/) {
                   2120:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2121:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2122:                   if ($mresponse->is_error()) {
                   2123: 		      unlink($filename.'.meta');
                   2124:                       &logthis(
1.672     albertel 2125:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2126:                   }
                   2127: 	       }
1.8       www      2128:                rename($transname,$filename);
1.607     raeburn  2129:                return 'ok';
1.8       www      2130:            }
1.290     www      2131:        }
1.8       www      2132:     }
1.330     www      2133: }
                   2134: 
                   2135: # ------------------------------------------------ Get server side include body
                   2136: sub ssi_body {
1.381     albertel 2137:     my ($filelink,%form)=@_;
1.606     matthew  2138:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2139:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2140:     }
1.953     www      2141:     my $output='';
                   2142:     my $response;
1.980     raeburn  2143:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2144:        ($output,$response)=&externalssi($filelink);
1.953     www      2145:     } else {
1.1004    droeschl 2146:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2147:        $filelink .= 'inhibitmenu=yes';
1.953     www      2148:        ($output,$response)=&ssi($filelink,%form);
                   2149:     }
1.778     albertel 2150:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2151:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2152:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2153:     if (wantarray) {
                   2154:         return ($output, $response);
                   2155:     } else {
                   2156:         return $output;
                   2157:     }
1.8       www      2158: }
                   2159: 
1.15      www      2160: # --------------------------------------------------------- Server Side Include
                   2161: 
1.782     albertel 2162: sub absolute_url {
                   2163:     my ($host_name) = @_;
                   2164:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2165:     if ($host_name eq '') {
                   2166: 	$host_name = $ENV{'SERVER_NAME'};
                   2167:     }
                   2168:     return $protocol.$host_name;
                   2169: }
                   2170: 
1.942     foxr     2171: #
                   2172: #   Server side include.
                   2173: # Parameters:
                   2174: #  fn     Possibly encrypted resource name/id.
                   2175: #  form   Hash that describes how the rendering should be done
                   2176: #         and other things.
1.944     foxr     2177: # Returns:
1.950     raeburn  2178: #   Scalar context: The content of the response.
                   2179: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2180: #     
1.15      www      2181: sub ssi {
                   2182: 
1.944     foxr     2183:     my ($fn,%form)=@_;
1.15      www      2184:     my $ua=new LWP::UserAgent;
1.23      www      2185:     my $request;
1.711     albertel 2186: 
                   2187:     $form{'no_update_last_known'}=1;
1.895     albertel 2188:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2189:     if (%form) {
1.782     albertel 2190:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2191:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2192:     } else {
1.782     albertel 2193:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2194:     }
                   2195: 
1.15      www      2196:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2197:     my $response=$ua->request($request);
                   2198: 
1.944     foxr     2199:     if (wantarray) {
                   2200: 	return ($response->content, $response);
                   2201:     } else {
                   2202: 	return $response->content;
1.942     foxr     2203:     }
1.324     www      2204: }
                   2205: 
                   2206: sub externalssi {
                   2207:     my ($url)=@_;
                   2208:     my $ua=new LWP::UserAgent;
                   2209:     my $request=new HTTP::Request('GET',$url);
                   2210:     my $response=$ua->request($request);
1.954     raeburn  2211:     if (wantarray) {
                   2212:         return ($response->content, $response);
                   2213:     } else {
                   2214:         return $response->content;
                   2215:     }
1.15      www      2216: }
1.254     www      2217: 
1.492     albertel 2218: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2219: 
                   2220: sub allowuploaded {
                   2221:     my ($srcurl,$url)=@_;
                   2222:     $url=&clutter(&declutter($url));
                   2223:     my $dir=$url;
                   2224:     $dir=~s/\/[^\/]+$//;
                   2225:     my %httpref=();
                   2226:     my $httpurl=&hreflocation('',$url);
                   2227:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2228:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2229: }
1.477     raeburn  2230: 
1.478     albertel 2231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2232: # input: action, courseID, current domain, intended
1.637     raeburn  2233: #        path to file, source of file, instruction to parse file for objects,
                   2234: #        ref to hash for embedded objects,
                   2235: #        ref to hash for codebase of java objects.
1.1095    raeburn  2236: #        reference to scalar to accommodate mime type determined
                   2237: #          from File::MMagic if $parser = parse.
1.637     raeburn  2238: #
1.485     raeburn  2239: # output: url to file (if action was uploaddoc), 
                   2240: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2241: #
1.478     albertel 2242: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2243: # course.
1.477     raeburn  2244: #
1.478     albertel 2245: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2246: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2247: #          course's home server.
1.477     raeburn  2248: #
1.478     albertel 2249: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2250: #          be copied from $source (current location) to 
                   2251: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2252: #         and will then be copied to
                   2253: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2254: #         course's home server.
1.485     raeburn  2255: #
1.481     raeburn  2256: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2257: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2258: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2259: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2260: #         in course's home server.
1.637     raeburn  2261: #
1.477     raeburn  2262: 
                   2263: sub process_coursefile {
1.1095    raeburn  2264:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2265:         $mimetype)=@_;
1.477     raeburn  2266:     my $fetchresult;
1.638     albertel 2267:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2268:     if ($action eq 'propagate') {
1.638     albertel 2269:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2270: 			     $home);
1.481     raeburn  2271:     } else {
1.477     raeburn  2272:         my $fpath = '';
                   2273:         my $fname = $file;
1.478     albertel 2274:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2275:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2276:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2277:         if ($action eq 'copy') {
                   2278:             if ($source eq '') {
                   2279:                 $fetchresult = 'no source file';
                   2280:                 return $fetchresult;
                   2281:             } else {
                   2282:                 my $destination = $filepath.'/'.$fname;
                   2283:                 rename($source,$destination);
                   2284:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2285:                                  $home);
1.481     raeburn  2286:             }
                   2287:         } elsif ($action eq 'uploaddoc') {
                   2288:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2289:             print $fh $env{'form.'.$source};
1.481     raeburn  2290:             close($fh);
1.637     raeburn  2291:             if ($parser eq 'parse') {
1.1024    raeburn  2292:                 my $mm = new File::MMagic;
1.1095    raeburn  2293:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2294:                 if ($type eq 'text/html') {
1.1024    raeburn  2295:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2296:                     unless ($parse_result eq 'ok') {
                   2297:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2298:                     }
1.637     raeburn  2299:                 }
1.1095    raeburn  2300:                 if (ref($mimetype)) {
                   2301:                     $$mimetype = $type;
                   2302:                 } 
1.637     raeburn  2303:             }
1.477     raeburn  2304:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2305:                                  $home);
1.481     raeburn  2306:             if ($fetchresult eq 'ok') {
                   2307:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2308:             } else {
                   2309:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2310:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2311:                 return '/adm/notfound.html';
                   2312:             }
1.477     raeburn  2313:         }
                   2314:     }
1.485     raeburn  2315:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2316:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2317:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2318:     }
                   2319:     return $fetchresult;
                   2320: }
                   2321: 
1.637     raeburn  2322: sub build_filepath {
                   2323:     my ($fpath) = @_;
                   2324:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2325:     unless ($fpath eq '') {
                   2326:         my @parts=split('/',$fpath);
                   2327:         foreach my $part (@parts) {
                   2328:             $filepath.= '/'.$part;
                   2329:             if ((-e $filepath)!=1) {
                   2330:                 mkdir($filepath,0777);
                   2331:             }
                   2332:         }
                   2333:     }
                   2334:     return $filepath;
                   2335: }
                   2336: 
                   2337: sub store_edited_file {
1.638     albertel 2338:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2339:     my $file = $primary_url;
                   2340:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2341:     my $fpath = '';
                   2342:     my $fname = $file;
                   2343:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2344:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2345:     my $filepath = &build_filepath($fpath);
                   2346:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2347:     print $fh $content;
                   2348:     close($fh);
1.638     albertel 2349:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2350:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2351: 			  $home);
1.637     raeburn  2352:     if ($$fetchresult eq 'ok') {
                   2353:         return '/uploaded/'.$fpath.'/'.$fname;
                   2354:     } else {
1.638     albertel 2355:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2356: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2357:         return '/adm/notfound.html';
                   2358:     }
                   2359: }
                   2360: 
1.531     albertel 2361: sub clean_filename {
1.831     albertel 2362:     my ($fname,$args)=@_;
1.315     www      2363: # Replace Windows backslashes by forward slashes
1.257     www      2364:     $fname=~s/\\/\//g;
1.831     albertel 2365:     if (!$args->{'keep_path'}) {
                   2366:         # Get rid of everything but the actual filename
                   2367: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2368:     }
1.315     www      2369: # Replace spaces by underscores
                   2370:     $fname=~s/\s+/\_/g;
                   2371: # Replace all other weird characters by nothing
1.831     albertel 2372:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2373: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2374: # numbers
                   2375:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2376:     return $fname;
                   2377: }
1.1051    raeburn  2378: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2379: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2380: # image with the same aspect ratio as the original, but with dimensions which do 
                   2381: # not exceed $resizewidth and $resizeheight.
                   2382:  
1.984     neumanie 2383: sub resizeImage {
1.1051    raeburn  2384:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2385:     my $ima = Image::Magick->new;
                   2386:     my $resized;
                   2387:     if (-e $img_path) {
                   2388:         $ima->Read($img_path);
                   2389:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2390:             my $width = $ima->Get('width');
                   2391:             my $height = $ima->Get('height');
                   2392:             if ($width > $resizewidth) {
                   2393: 	        my $factor = $width/$resizewidth;
                   2394:                 my $newheight = $height/$factor;
                   2395:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2396:                 $resized = 1;
                   2397:             }
                   2398:         }
                   2399:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2400:             my $width = $ima->Get('width');
                   2401:             my $height = $ima->Get('height');
                   2402:             if ($height > $resizeheight) {
                   2403:                 my $factor = $height/$resizeheight;
                   2404:                 my $newwidth = $width/$factor;
                   2405:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2406:                 $resized = 1;
                   2407:             }
                   2408:         }
                   2409:         if ($resized) {
                   2410:             $ima->Write($img_path);
                   2411:         }
                   2412:     }
                   2413:     return;
1.977     amueller 2414: }
                   2415: 
1.608     albertel 2416: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2417: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2418: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2419: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2420: #                                    canceloverwrite, or ''. 
                   2421: #                   if 'coursedoc': upload to the current course
                   2422: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2423: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2424: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2425: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2426: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2427: #        $allfiles - reference to hash for embedded objects
                   2428: #        $codebase - reference to hash for codebase of java objects
                   2429: #        $desuname - username for permanent storage of uploaded file
                   2430: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2431: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2432: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2433: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2434: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2435: #        $mimetype - reference to scalar to accommodate mime type determined
                   2436: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2437: # 
1.686     albertel 2438: # output: url of file in userspace, or error: <message> 
                   2439: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2440: 
1.531     albertel 2441: sub userfileupload {
1.1090    raeburn  2442:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2443:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2444:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2445:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2446:     $fname=&clean_filename($fname);
1.1090    raeburn  2447:     # See if there is anything left
1.257     www      2448:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2449:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2450:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2451:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2452:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2453:         my $now = time;
1.1090    raeburn  2454:         my $filepath;
1.1095    raeburn  2455:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2456:              $filepath = 'tmp/helprequests/'.$now;
                   2457:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2458:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2459:                          '_'.$env{'user.domain'}.'/pending';
                   2460:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2461:             my ($docuname,$docudom);
                   2462:             if ($destudom) {
                   2463:                 $docudom = $destudom;
                   2464:             } else {
                   2465:                 $docudom = $env{'user.domain'};
                   2466:             }
                   2467:             if ($destuname) {
                   2468:                 $docuname = $destuname;
                   2469:             } else {
                   2470:                 $docuname = $env{'user.name'};
                   2471:             }
                   2472:             if (exists($env{'form.group'})) {
                   2473:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2474:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2475:             }
                   2476:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2477:             if ($context eq 'canceloverwrite') {
                   2478:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2479:                 if (-e  $tempfile) {
                   2480:                     my @info = stat($tempfile);
                   2481:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2482:                         unlink($tempfile);
                   2483:                     }
                   2484:                 }
                   2485:                 return;
1.523     raeburn  2486:             }
                   2487:         }
1.1090    raeburn  2488:         # Create the directory if not present
1.741     raeburn  2489:         my @parts=split(/\//,$filepath);
                   2490:         my $fullpath = $perlvar{'lonDaemons'};
                   2491:         for (my $i=0;$i<@parts;$i++) {
                   2492:             $fullpath .= '/'.$parts[$i];
                   2493:             if ((-e $fullpath)!=1) {
                   2494:                 mkdir($fullpath,0777);
                   2495:             }
                   2496:         }
                   2497:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2498:         print $fh $env{'form.'.$formname};
                   2499:         close($fh);
1.1090    raeburn  2500:         if ($context eq 'existingfile') {
                   2501:             my @info = stat($fullpath.'/'.$fname);
                   2502:             return ($fullpath.'/'.$fname,$info[9]);
                   2503:         } else {
                   2504:             return $fullpath.'/'.$fname;
                   2505:         }
1.523     raeburn  2506:     }
1.995     raeburn  2507:     if ($subdir eq 'scantron') {
                   2508:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2509:     } else {
1.995     raeburn  2510:         $fname="$subdir/$fname";
                   2511:     }
1.1090    raeburn  2512:     if ($context eq 'coursedoc') {
1.638     albertel 2513: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2514: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2515:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2516:             return &finishuserfileupload($docuname,$docudom,
                   2517: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2518: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2519:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2520:         } else {
1.620     albertel 2521:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2522:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2523: 				       $fname,$formname,$parser,
1.1095    raeburn  2524: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2525:         }
1.719     banghart 2526:     } elsif (defined($destuname)) {
                   2527:         my $docuname=$destuname;
                   2528:         my $docudom=$destudom;
1.860     raeburn  2529: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2530: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2531:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2532:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2533:     } else {
1.638     albertel 2534:         my $docuname=$env{'user.name'};
                   2535:         my $docudom=$env{'user.domain'};
1.714     raeburn  2536:         if (exists($env{'form.group'})) {
                   2537:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2538:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2539:         }
1.860     raeburn  2540: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2541: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2542:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2543:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2544:     }
1.271     www      2545: }
                   2546: 
                   2547: sub finishuserfileupload {
1.860     raeburn  2548:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2549:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2550:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2551:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2552:   
1.860     raeburn  2553:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2554:     $file=$fname;
                   2555:     if ($fname=~m|/|) {
                   2556:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2557: 	$path.=$fnamepath.'/';
                   2558:     }
1.259     www      2559:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2560:     my $count;
                   2561:     for ($count=4;$count<=$#parts;$count++) {
                   2562:         $filepath.="/$parts[$count]";
                   2563:         if ((-e $filepath)!=1) {
                   2564: 	    mkdir($filepath,0777);
                   2565:         }
                   2566:     }
1.984     neumanie 2567: 
1.258     www      2568: # Save the file
                   2569:     {
1.701     albertel 2570: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2571: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2572: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2573: 	    return '/adm/notfound.html';
                   2574: 	}
1.1090    raeburn  2575:         if ($context eq 'overwrite') {
                   2576:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2577:             my $target = $filepath.'/'.$file;
                   2578:             if (-e $source) {
                   2579:                 my @info = stat($source);
                   2580:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2581:                     unless (&File::Copy::move($source,$target)) {
                   2582:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2583:                         return "Moving from $source failed";
                   2584:                     }
                   2585:                 } else {
                   2586:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2587:                 }
                   2588:             } else {
                   2589:                 return "Temporary file: $source missing";
                   2590:             }
                   2591:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2592: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2593: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2594: 	    return '/adm/notfound.html';
                   2595: 	}
1.570     albertel 2596: 	close(FH);
1.1051    raeburn  2597:         if ($resizewidth && $resizeheight) {
                   2598:             my $mm = new File::MMagic;
                   2599:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2600:             if ($mime_type =~ m{^image/}) {
                   2601: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2602:             }  
1.977     amueller 2603: 	}
1.258     www      2604:     }
1.637     raeburn  2605:     if ($parser eq 'parse') {
1.1024    raeburn  2606:         my $mm = new File::MMagic;
1.1095    raeburn  2607:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2608:         if ($type eq 'text/html') {
1.1024    raeburn  2609:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2610:                                                        $allfiles,$codebase);
                   2611:             unless ($parse_result eq 'ok') {
                   2612:                 &logthis('Failed to parse '.$filepath.$file.
                   2613: 	   	         ' for embedded media: '.$parse_result); 
                   2614:             }
1.637     raeburn  2615:         }
1.1095    raeburn  2616:         if (ref($mimetype)) {
                   2617:             $$mimetype = $type;
                   2618:         }
1.637     raeburn  2619:     }
1.860     raeburn  2620:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2621:         my $input = $filepath.'/'.$file;
                   2622:         my $output = $filepath.'/'.'tn-'.$file;
                   2623:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2624:         system("convert -sample $thumbsize $input $output");
                   2625:         if (-e $filepath.'/'.'tn-'.$file) {
                   2626:             $fetchthumb  = 1; 
                   2627:         }
                   2628:     }
1.858     raeburn  2629:  
1.259     www      2630: # Notify homeserver to grep it
                   2631: #
1.984     neumanie 2632:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2633:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2634:     if ($fetchresult eq 'ok') {
1.860     raeburn  2635:         if ($fetchthumb) {
                   2636:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2637:             if ($thumbresult ne 'ok') {
                   2638:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2639:                          $docuhome.': '.$thumbresult);
                   2640:             }
                   2641:         }
1.259     www      2642: #
1.258     www      2643: # Return the URL to it
1.494     albertel 2644:         return '/uploaded/'.$path.$file;
1.263     www      2645:     } else {
1.494     albertel 2646:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2647: 		 ': '.$fetchresult);
1.263     www      2648:         return '/adm/notfound.html';
1.858     raeburn  2649:     }
1.493     albertel 2650: }
                   2651: 
1.637     raeburn  2652: sub extract_embedded_items {
1.961     raeburn  2653:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2654:     my @state = ();
                   2655:     my %javafiles = (
                   2656:                       codebase => '',
                   2657:                       code => '',
                   2658:                       archive => ''
                   2659:                     );
                   2660:     my %mediafiles = (
                   2661:                       src => '',
                   2662:                       movie => '',
                   2663:                      );
1.648     raeburn  2664:     my $p;
                   2665:     if ($content) {
                   2666:         $p = HTML::LCParser->new($content);
                   2667:     } else {
1.961     raeburn  2668:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2669:     }
1.641     albertel 2670:     while (my $t=$p->get_token()) {
1.640     albertel 2671: 	if ($t->[0] eq 'S') {
                   2672: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2673: 	    push(@state, $tagname);
1.648     raeburn  2674:             if (lc($tagname) eq 'allow') {
                   2675:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2676:             }
1.640     albertel 2677: 	    if (lc($tagname) eq 'img') {
                   2678: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2679: 	    }
1.886     albertel 2680: 	    if (lc($tagname) eq 'a') {
                   2681: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2682: 	    }
1.645     raeburn  2683:             if (lc($tagname) eq 'script') {
                   2684:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2685:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2686:                 } else {
                   2687:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2688:                 }
                   2689:             }
                   2690:             if (lc($tagname) eq 'link') {
                   2691:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2692:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2693:                 }
                   2694:             }
1.640     albertel 2695: 	    if (lc($tagname) eq 'object' ||
                   2696: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2697: 		foreach my $item (keys(%javafiles)) {
                   2698: 		    $javafiles{$item} = '';
                   2699: 		}
                   2700: 	    }
                   2701: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2702: 		my $name = lc($attr->{'name'});
                   2703: 		foreach my $item (keys(%javafiles)) {
                   2704: 		    if ($name eq $item) {
                   2705: 			$javafiles{$item} = $attr->{'value'};
                   2706: 			last;
                   2707: 		    }
                   2708: 		}
                   2709: 		foreach my $item (keys(%mediafiles)) {
                   2710: 		    if ($name eq $item) {
                   2711: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2712: 			last;
                   2713: 		    }
                   2714: 		}
                   2715: 	    }
                   2716: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2717: 		foreach my $item (keys(%javafiles)) {
                   2718: 		    if ($attr->{$item}) {
                   2719: 			$javafiles{$item} = $attr->{$item};
                   2720: 			last;
                   2721: 		    }
                   2722: 		}
                   2723: 		foreach my $item (keys(%mediafiles)) {
                   2724: 		    if ($attr->{$item}) {
                   2725: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2726: 			last;
                   2727: 		    }
                   2728: 		}
                   2729: 	    }
                   2730: 	} elsif ($t->[0] eq 'E') {
                   2731: 	    my ($tagname) = ($t->[1]);
                   2732: 	    if ($javafiles{'codebase'} ne '') {
                   2733: 		$javafiles{'codebase'} .= '/';
                   2734: 	    }  
                   2735: 	    if (lc($tagname) eq 'applet' ||
                   2736: 		lc($tagname) eq 'object' ||
                   2737: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2738: 		) {
                   2739: 		foreach my $item (keys(%javafiles)) {
                   2740: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2741: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2742: 			&add_filetype($allfiles,$file,$item);
                   2743: 		    }
                   2744: 		}
                   2745: 	    } 
                   2746: 	    pop @state;
                   2747: 	}
                   2748:     }
1.637     raeburn  2749:     return 'ok';
                   2750: }
                   2751: 
1.639     albertel 2752: sub add_filetype {
                   2753:     my ($allfiles,$file,$type)=@_;
                   2754:     if (exists($allfiles->{$file})) {
                   2755: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2756: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2757: 	}
                   2758:     } else {
                   2759: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2760:     }
                   2761: }
                   2762: 
1.493     albertel 2763: sub removeuploadedurl {
1.984     neumanie 2764:     my ($url)=@_;	
                   2765:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2766:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2767: }
                   2768: 
                   2769: sub removeuserfile {
                   2770:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2771:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2772:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2773:     if ($result eq 'ok') {	
1.798     raeburn  2774:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2775:             my $metafile = $fname.'.meta';
                   2776:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2777: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2778:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2779:             my $sqlresult = 
1.823     albertel 2780:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2781:                                         'portfolio_metadata',$group,
                   2782:                                         'delete');
1.798     raeburn  2783:         }
                   2784:     }
                   2785:     return $result;
1.257     www      2786: }
1.15      www      2787: 
1.530     albertel 2788: sub mkdiruserfile {
                   2789:     my ($docuname,$docudom,$dir)=@_;
                   2790:     my $home=&homeserver($docuname,$docudom);
                   2791:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2792: }
                   2793: 
1.531     albertel 2794: sub renameuserfile {
                   2795:     my ($docuname,$docudom,$old,$new)=@_;
                   2796:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2797:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2798:                         &escape("$old").':'.&escape("$new"),$home);
                   2799:     if ($result eq 'ok') {
                   2800:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2801:             my $oldmeta = $old.'.meta';
                   2802:             my $newmeta = $new.'.meta';
                   2803:             my $metaresult = 
                   2804:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2805: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2806:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2807:             my $sqlresult = 
1.823     albertel 2808:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2809:                                         'portfolio_metadata',$group,
                   2810:                                         'delete');
1.798     raeburn  2811:         }
                   2812:     }
                   2813:     return $result;
1.531     albertel 2814: }
                   2815: 
1.14      www      2816: # ------------------------------------------------------------------------- Log
                   2817: 
                   2818: sub log {
                   2819:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2820:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2821: }
                   2822: 
                   2823: # ------------------------------------------------------------------ Course Log
1.352     www      2824: #
                   2825: # This routine flushes several buffers of non-mission-critical nature
                   2826: #
1.157     www      2827: 
                   2828: sub flushcourselogs {
1.352     www      2829:     &logthis('Flushing log buffers');
                   2830: #
                   2831: # course logs
                   2832: # This is a log of all transactions in a course, which can be used
                   2833: # for data mining purposes
                   2834: #
                   2835: # It also collects the courseid database, which lists last transaction
                   2836: # times and course titles for all courseids
                   2837: #
                   2838:     my %courseidbuffer=();
1.921     raeburn  2839:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2840:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2841: 		          &escape($courselogs{$crsid}),
                   2842: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2843: 	    delete $courselogs{$crsid};
                   2844:         } else {
                   2845:             &logthis('Failed to flush log buffer for '.$crsid);
                   2846:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2847:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2848:                         " exceeded maximum size, deleting.</font>");
                   2849:                delete $courselogs{$crsid};
                   2850:             }
1.352     www      2851:         }
1.920     raeburn  2852:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2853:             'description' => $coursedescrbuf{$crsid},
                   2854:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2855:             'type'        => $coursetypebuf{$crsid},
                   2856:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2857:         };
1.191     harris41 2858:     }
1.352     www      2859: #
                   2860: # Write course id database (reverse lookup) to homeserver of courses 
                   2861: # Is used in pickcourse
                   2862: #
1.840     albertel 2863:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2864:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2865:                                     $courseidbuffer{$crs_home},
                   2866:                                     $crs_home,'timeonly');
1.352     www      2867:     }
                   2868: #
                   2869: # File accesses
                   2870: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2871: #
1.449     matthew  2872:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2873:         if ($entry =~ /___count$/) {
                   2874:             my ($dom,$name);
1.807     albertel 2875:             ($dom,$name,undef)=
1.811     albertel 2876: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2877:             if (! defined($dom) || $dom eq '' || 
                   2878:                 ! defined($name) || $name eq '') {
1.620     albertel 2879:                 my $cid = $env{'request.course.id'};
                   2880:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2881:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2882:             }
1.450     matthew  2883:             my $value = $accesshash{$entry};
                   2884:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2885:             my %temphash=($url => $value);
1.449     matthew  2886:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2887:             if ($result eq 'ok') {
                   2888:                 delete $accesshash{$entry};
                   2889:             } elsif ($result eq 'unknown_cmd') {
                   2890:                 # Target server has old code running on it.
1.450     matthew  2891:                 my %temphash=($entry => $value);
1.449     matthew  2892:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2893:                     delete $accesshash{$entry};
                   2894:                 }
                   2895:             }
                   2896:         } else {
1.811     albertel 2897:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2898:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2899:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2900:                 delete $accesshash{$entry};
                   2901:             }
1.185     www      2902:         }
1.191     harris41 2903:     }
1.352     www      2904: #
                   2905: # Roles
                   2906: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2907: #
1.800     albertel 2908:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2909:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2910: 	    split(/\:/,$entry);
                   2911:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2912:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2913:                 $rudom,$runame) eq 'ok') {
                   2914: 	    delete $userrolehash{$entry};
                   2915:         }
                   2916:     }
1.662     raeburn  2917: #
                   2918: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2919: #
                   2920:     my %domrolebuffer = ();
1.1000    raeburn  2921:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2922:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2923:         if ($domrolebuffer{$rudom}) {
                   2924:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2925:                       '='.&escape($domainrolehash{$entry});
                   2926:         } else {
                   2927:             $domrolebuffer{$rudom}.=&escape($entry).
                   2928:                       '='.&escape($domainrolehash{$entry});
                   2929:         }
                   2930:         delete $domainrolehash{$entry};
                   2931:     }
                   2932:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2933: 	my %servers = &get_servers($dom,'library');
                   2934: 	foreach my $tryserver (keys(%servers)) {
                   2935: 	    unless (&reply('domroleput:'.$dom.':'.
                   2936: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2937: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2938: 	    }
1.662     raeburn  2939:         }
                   2940:     }
1.186     www      2941:     $dumpcount++;
1.157     www      2942: }
                   2943: 
                   2944: sub courselog {
                   2945:     my $what=shift;
1.158     www      2946:     $what=time.':'.$what;
1.620     albertel 2947:     unless ($env{'request.course.id'}) { return ''; }
                   2948:     $coursedombuf{$env{'request.course.id'}}=
                   2949:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2950:     $coursenumbuf{$env{'request.course.id'}}=
                   2951:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2952:     $coursehombuf{$env{'request.course.id'}}=
                   2953:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2954:     $coursedescrbuf{$env{'request.course.id'}}=
                   2955:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2956:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2957:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2958:     $courseownerbuf{$env{'request.course.id'}}=
                   2959:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2960:     $coursetypebuf{$env{'request.course.id'}}=
                   2961:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2962:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2963: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2964:     } else {
1.620     albertel 2965: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2966:     }
1.620     albertel 2967:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2968: 	&flushcourselogs();
                   2969:     }
1.158     www      2970: }
                   2971: 
                   2972: sub courseacclog {
                   2973:     my $fnsymb=shift;
1.620     albertel 2974:     unless ($env{'request.course.id'}) { return ''; }
                   2975:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2976:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2977:         $what.=':POST';
1.583     matthew  2978:         # FIXME: Probably ought to escape things....
1.800     albertel 2979: 	foreach my $key (keys(%env)) {
                   2980:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2981:                 my $formitem = $1;
                   2982:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2983:                     $what.=':'.$formitem.'='.$env{$key};
                   2984:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2985:                     $what.=':'.$formitem.'='.$env{$key};
                   2986:                 }
1.158     www      2987:             }
1.191     harris41 2988:         }
1.583     matthew  2989:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2990:         # FIXME: We should not be depending on a form parameter that someone
                   2991:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2992:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2993:             $what.= ':POST';
                   2994:             # FIXME: Probably ought to escape things....
                   2995:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2996:                                  'crsdiscuss') {
1.620     albertel 2997:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2998:             }
                   2999:         }
1.158     www      3000:     }
                   3001:     &courselog($what);
1.149     www      3002: }
                   3003: 
1.185     www      3004: sub countacc {
                   3005:     my $url=&declutter(shift);
1.458     matthew  3006:     return if (! defined($url) || $url eq '');
1.620     albertel 3007:     unless ($env{'request.course.id'}) { return ''; }
                   3008:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3009:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3010:     $accesshash{$key}++;
1.185     www      3011: }
1.349     www      3012: 
1.361     www      3013: sub linklog {
                   3014:     my ($from,$to)=@_;
                   3015:     $from=&declutter($from);
                   3016:     $to=&declutter($to);
                   3017:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3018:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3019: }
                   3020:   
1.349     www      3021: sub userrolelog {
                   3022:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3023:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3024:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3025:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3026:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3027:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3028:        $userrolehash
                   3029:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3030:                     =$tend.':'.$tstart;
1.662     raeburn  3031:     }
1.898     albertel 3032:     if (($env{'request.role'} =~ /dc\./) &&
                   3033: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3034: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3035: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3036:          ($trole=~/^co/))) {
1.898     albertel 3037:        $userrolehash
                   3038:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3039:                     =$tend.':'.$tstart;
                   3040:     }
1.662     raeburn  3041:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3042:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3043:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3044:         ($trole=~/^sc/)) {
                   3045:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3046:        $domainrolehash
                   3047:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3048:                     = $tend.':'.$tstart;
                   3049:     }
1.351     www      3050: }
                   3051: 
1.957     raeburn  3052: sub courserolelog {
                   3053:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3054:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3055:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3056:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3057:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3058:         ($trole eq 'co')) {
1.957     raeburn  3059:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3060:             my $cdom = $1;
                   3061:             my $cnum = $2;
                   3062:             my $sec = $3;
                   3063:             my $namespace = 'rolelog';
                   3064:             my %storehash = (
                   3065:                                role    => $trole,
                   3066:                                start   => $tstart,
                   3067:                                end     => $tend,
                   3068:                                selfenroll => $selfenroll,
                   3069:                                context    => $context,
                   3070:                             );
                   3071:             if ($trole eq 'gr') {
                   3072:                 $namespace = 'groupslog';
                   3073:                 $storehash{'group'} = $sec;
                   3074:             } else {
                   3075:                 $storehash{'section'} = $sec;
                   3076:             }
                   3077:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3078:             if (($trole ne 'st') || ($sec ne '')) {
                   3079:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3080:             }
1.957     raeburn  3081:         }
                   3082:     }
                   3083:     return;
                   3084: }
                   3085: 
1.351     www      3086: sub get_course_adv_roles {
1.948     raeburn  3087:     my ($cid,$codes) = @_;
1.620     albertel 3088:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3089:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3090:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3091:     my %nothide=();
1.800     albertel 3092:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3093:         if ($user !~ /:/) {
                   3094: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3095:         } else {
                   3096:             $nothide{$user}=1;
                   3097:         }
1.470     www      3098:     }
1.351     www      3099:     my %returnhash=();
                   3100:     my %dumphash=
                   3101:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3102:     my $now=time;
1.997     raeburn  3103:     my %privileged;
1.1000    raeburn  3104:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3105: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3106:         if (($tstart) && ($tstart<0)) { next; }
                   3107:         if (($tend) && ($tend<$now)) { next; }
                   3108:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3109:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3110: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3111:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3112:             my %dompersonnel =
1.998     raeburn  3113:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3114:             $privileged{$domain} = {};
                   3115:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3116:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3117:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3118:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3119:                         $privileged{$udom}{$uname} = 1;
                   3120:                     }
                   3121:                 }
                   3122:             }
                   3123:         }
                   3124:         if ((exists($privileged{$domain}{$username})) && 
                   3125:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3126: 	if ($role eq 'cr') { next; }
1.948     raeburn  3127:         if ($codes) {
                   3128:             if ($section) { $role .= ':'.$section; }
                   3129:             if ($returnhash{$role}) {
                   3130:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3131:             } else {
                   3132:                 $returnhash{$role}=$username.':'.$domain;
                   3133:             }
1.351     www      3134:         } else {
1.988     raeburn  3135:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3136:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3137:             if ($returnhash{$key}) {
                   3138: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3139:             } else {
                   3140:                 $returnhash{$key}=$username.':'.$domain;
                   3141:             }
1.351     www      3142:         }
1.948     raeburn  3143:     }
1.400     www      3144:     return %returnhash;
                   3145: }
                   3146: 
                   3147: sub get_my_roles {
1.937     raeburn  3148:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3149:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3150:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3151:     my (%dumphash,%nothide);
1.1086    raeburn  3152:     if ($context eq 'userroles') {
                   3153:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3154:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3155:     } else {
                   3156:         %dumphash=
1.400     www      3157:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3158:         if ($hidepriv) {
                   3159:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3160:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3161:                 if ($user !~ /:/) {
                   3162:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3163:                 } else {
                   3164:                     $nothide{$user} = 1;
                   3165:                 }
                   3166:             }
                   3167:         }
1.858     raeburn  3168:     }
1.400     www      3169:     my %returnhash=();
                   3170:     my $now=time;
1.999     raeburn  3171:     my %privileged;
1.800     albertel 3172:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3173:         my ($role,$tend,$tstart);
                   3174:         if ($context eq 'userroles') {
                   3175: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3176:         } else {
                   3177:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3178:         }
1.400     www      3179:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3180:         my $status = 'active';
1.939     raeburn  3181:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3182:             $status = 'previous';
                   3183:         } 
                   3184:         if (($tstart) && ($now<$tstart)) {
                   3185:             $status = 'future';
                   3186:         }
                   3187:         if (ref($types) eq 'ARRAY') {
                   3188:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3189:                 next;
                   3190:             } 
                   3191:         } else {
                   3192:             if ($status ne 'active') {
                   3193:                 next;
                   3194:             }
                   3195:         }
1.867     raeburn  3196:         my ($rolecode,$username,$domain,$section,$area);
                   3197:         if ($context eq 'userroles') {
                   3198:             ($area,$rolecode) = split(/_/,$entry);
                   3199:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3200:         } else {
                   3201:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3202:         }
1.832     raeburn  3203:         if (ref($roledoms) eq 'ARRAY') {
                   3204:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3205:                 next;
                   3206:             }
                   3207:         }
                   3208:         if (ref($roles) eq 'ARRAY') {
                   3209:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3210:                 if ($role =~ /^cr\//) {
                   3211:                     if (!grep(/^cr$/,@{$roles})) {
                   3212:                         next;
                   3213:                     }
1.1104    raeburn  3214:                 } elsif ($role =~ /^gr\//) {
                   3215:                     if (!grep(/^gr$/,@{$roles})) {
                   3216:                         next;
                   3217:                     }
1.922     raeburn  3218:                 } else {
                   3219:                     next;
                   3220:                 }
1.832     raeburn  3221:             }
1.867     raeburn  3222:         }
1.937     raeburn  3223:         if ($hidepriv) {
1.999     raeburn  3224:             if ($context eq 'userroles') {
                   3225:                 if ((&privileged($username,$domain)) &&
                   3226:                     (!$nothide{$username.':'.$domain})) {
                   3227:                     next;
                   3228:                 }
                   3229:             } else {
                   3230:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3231:                     my %dompersonnel =
                   3232:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3233:                     $privileged{$domain} = {};
                   3234:                     if (keys(%dompersonnel)) {
                   3235:                         foreach my $server (keys(%dompersonnel)) {
                   3236:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3237:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3238:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3239:                                     $privileged{$udom}{$uname} = $trole;
                   3240:                                 }
                   3241:                             }
                   3242:                         }
                   3243:                     }
                   3244:                 }
                   3245:                 if (exists($privileged{$domain}{$username})) {
                   3246:                     if (!$nothide{$username.':'.$domain}) {
                   3247:                         next;
                   3248:                     }
                   3249:                 }
1.937     raeburn  3250:             }
                   3251:         }
1.933     raeburn  3252:         if ($withsec) {
                   3253:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3254:                 $tstart.':'.$tend;
                   3255:         } else {
                   3256:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3257:         }
1.832     raeburn  3258:     }
1.373     www      3259:     return %returnhash;
1.399     www      3260: }
                   3261: 
                   3262: # ----------------------------------------------------- Frontpage Announcements
                   3263: #
                   3264: #
                   3265: 
                   3266: sub postannounce {
                   3267:     my ($server,$text)=@_;
1.844     albertel 3268:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3269:     unless ($text=~/\w/) { $text=''; }
                   3270:     return &reply('setannounce:'.&escape($text),$server);
                   3271: }
                   3272: 
                   3273: sub getannounce {
1.448     albertel 3274: 
                   3275:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3276: 	my $announcement='';
1.800     albertel 3277: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3278: 	close($fh);
1.399     www      3279: 	if ($announcement=~/\w/) { 
                   3280: 	    return 
                   3281:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3282:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3283: 	} else {
                   3284: 	    return '';
                   3285: 	}
                   3286:     } else {
                   3287: 	return '';
                   3288:     }
1.351     www      3289: }
1.353     www      3290: 
                   3291: # ---------------------------------------------------------- Course ID routines
                   3292: # Deal with domain's nohist_courseid.db files
                   3293: #
                   3294: 
                   3295: sub courseidput {
1.921     raeburn  3296:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3297:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3298:     my $outcome;
                   3299:     if ($caller eq 'timeonly') {
                   3300:         my $cids = '';
                   3301:         foreach my $item (keys(%$storehash)) {
                   3302:             $cids.=&escape($item).'&';
                   3303:         }
                   3304:         $cids=~s/\&$//;
                   3305:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3306:                           $coursehome);       
                   3307:     } else {
                   3308:         my $items = '';
                   3309:         foreach my $item (keys(%$storehash)) {
                   3310:             $items.= &escape($item).'='.
                   3311:                      &freeze_escape($$storehash{$item}).'&';
                   3312:         }
                   3313:         $items=~s/\&$//;
                   3314:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3315:                           $coursehome);
1.918     raeburn  3316:     }
                   3317:     if ($outcome eq 'unknown_cmd') {
                   3318:         my $what;
                   3319:         foreach my $cid (keys(%$storehash)) {
                   3320:             $what .= &escape($cid).'=';
1.921     raeburn  3321:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3322:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3323:             }
                   3324:             $what =~ s/\:$/&/;
                   3325:         }
                   3326:         $what =~ s/\&$//;  
                   3327:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3328:     } else {
                   3329:         return $outcome;
                   3330:     }
1.353     www      3331: }
                   3332: 
                   3333: sub courseiddump {
1.921     raeburn  3334:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3335:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3336:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3337:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3338:     my $as_hash = 1;
                   3339:     my %returnhash;
                   3340:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3341:     my %libserv = &all_library();
                   3342:     foreach my $tryserver (keys(%libserv)) {
                   3343:         if ( (  $hostidflag == 1 
                   3344: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3345: 	     || (!defined($hostidflag)) ) {
                   3346: 
1.918     raeburn  3347: 	    if (($domfilter eq '') ||
                   3348: 		(&host_domain($tryserver) eq $domfilter)) {
                   3349:                 my $rep = 
                   3350:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3351:                          $sincefilter.':'.&escape($descfilter).':'.
                   3352:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3353:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3354:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3355:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3356:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3357:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3358:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3359:                          &escape($creationcontext).':'.$domcloner,
                   3360:                          $tryserver);
1.918     raeburn  3361:                 my @pairs=split(/\&/,$rep);
                   3362:                 foreach my $item (@pairs) {
                   3363:                     my ($key,$value)=split(/\=/,$item,2);
                   3364:                     $key = &unescape($key);
                   3365:                     next if ($key =~ /^error: 2 /);
                   3366:                     my $result = &thaw_unescape($value);
                   3367:                     if (ref($result) eq 'HASH') {
                   3368:                         $returnhash{$key}=$result;
                   3369:                     } else {
1.921     raeburn  3370:                         my @responses = split(/:/,$value);
                   3371:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3372:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3373:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3374:                         }
1.1008    raeburn  3375:                     }
1.353     www      3376:                 }
                   3377:             }
                   3378:         }
                   3379:     }
                   3380:     return %returnhash;
                   3381: }
                   3382: 
1.1055    raeburn  3383: sub courselastaccess {
                   3384:     my ($cdom,$cnum,$hostidref) = @_;
                   3385:     my %returnhash;
                   3386:     if ($cdom && $cnum) {
                   3387:         my $chome = &homeserver($cnum,$cdom);
                   3388:         if ($chome ne 'no_host') {
                   3389:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3390:             &extract_lastaccess(\%returnhash,$rep);
                   3391:         }
                   3392:     } else {
                   3393:         if (!$cdom) { $cdom=''; }
                   3394:         my %libserv = &all_library();
                   3395:         foreach my $tryserver (keys(%libserv)) {
                   3396:             if (ref($hostidref) eq 'ARRAY') {
                   3397:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3398:             } 
                   3399:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3400:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3401:                 &extract_lastaccess(\%returnhash,$rep);
                   3402:             }
                   3403:         }
                   3404:     }
                   3405:     return %returnhash;
                   3406: }
                   3407: 
                   3408: sub extract_lastaccess {
                   3409:     my ($returnhash,$rep) = @_;
                   3410:     if (ref($returnhash) eq 'HASH') {
                   3411:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3412:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3413:                  $rep eq '') {
                   3414:             my @pairs=split(/\&/,$rep);
                   3415:             foreach my $item (@pairs) {
                   3416:                 my ($key,$value)=split(/\=/,$item,2);
                   3417:                 $key = &unescape($key);
                   3418:                 next if ($key =~ /^error: 2 /);
                   3419:                 $returnhash->{$key} = &thaw_unescape($value);
                   3420:             }
                   3421:         }
                   3422:     }
                   3423:     return;
                   3424: }
                   3425: 
1.658     raeburn  3426: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3427: 
                   3428: sub dcmailput {
1.685     raeburn  3429:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3430:     my $status = &Apache::lonnet::critical(
1.740     www      3431:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3432:        &escape($message),$server);
1.662     raeburn  3433:     return $status;
                   3434: }
                   3435: 
1.658     raeburn  3436: sub dcmaildump {
                   3437:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3438:     my %returnhash=();
1.846     albertel 3439: 
                   3440:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3441:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3442:                                                          &escape($enddate).':';
                   3443: 	my @esc_senders=map { &escape($_)} @$senders;
                   3444: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3445: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3446:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3447:             if (($key) && ($value)) {
                   3448:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3449:             }
                   3450:         }
                   3451:     }
                   3452:     return %returnhash;
                   3453: }
1.662     raeburn  3454: # ---------------------------------------------------------- Domain roles
                   3455: 
                   3456: sub get_domain_roles {
                   3457:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3458:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3459:         $startdate = '.';
                   3460:     }
1.1018    raeburn  3461:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3462:         $enddate = '.';
                   3463:     }
1.922     raeburn  3464:     my $rolelist;
                   3465:     if (ref($roles) eq 'ARRAY') {
                   3466:         $rolelist = join(':',@{$roles});
                   3467:     }
1.662     raeburn  3468:     my %personnel = ();
1.841     albertel 3469: 
                   3470:     my %servers = &get_servers($dom,'library');
                   3471:     foreach my $tryserver (keys(%servers)) {
                   3472: 	%{$personnel{$tryserver}}=();
                   3473: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3474: 					    &escape($startdate).':'.
                   3475: 					    &escape($enddate).':'.
                   3476: 					    &escape($rolelist), $tryserver))) {
                   3477: 	    my ($key,$value) = split(/\=/,$line,2);
                   3478: 	    if (($key) && ($value)) {
                   3479: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3480: 	    }
                   3481: 	}
1.662     raeburn  3482:     }
                   3483:     return %personnel;
                   3484: }
1.658     raeburn  3485: 
1.1057    www      3486: # ----------------------------------------------------------- Interval timing 
1.149     www      3487: 
1.504     albertel 3488: sub get_first_access {
                   3489:     my ($type,$argsymb)=@_;
1.790     albertel 3490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3491:     if ($argsymb) { $symb=$argsymb; }
                   3492:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3493:     if ($type eq 'course') {
                   3494: 	$res='course';
                   3495:     } elsif ($type eq 'map') {
1.588     albertel 3496: 	$res=&symbread($map);
                   3497:     } else {
                   3498: 	$res=$symb;
                   3499:     }
                   3500:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3501:     return $times{"$courseid\0$res"};
1.504     albertel 3502: }
                   3503: 
                   3504: sub set_first_access {
                   3505:     my ($type)=@_;
1.790     albertel 3506:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3507:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3508:     if ($type eq 'course') {
                   3509: 	$res='course';
                   3510:     } elsif ($type eq 'map') {
1.588     albertel 3511: 	$res=&symbread($map);
                   3512:     } else {
                   3513: 	$res=$symb;
                   3514:     }
                   3515:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3516:     if (!$firstaccess) {
1.588     albertel 3517: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3518:     }
                   3519:     return 'already_set';
1.504     albertel 3520: }
                   3521: 
1.110     www      3522: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3523: 
                   3524: sub expirespread {
                   3525:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3526:     my $cid=$env{'request.course.id'}; 
1.110     www      3527:     if ($cid) {
                   3528:        my $now=time;
                   3529:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3530:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3531:                             $env{'course.'.$cid.'.num'}.
1.110     www      3532: 	        	    ':nohist_expirationdates:'.
                   3533:                             &escape($key).'='.$now,
1.620     albertel 3534:                             $env{'course.'.$cid.'.home'})
1.110     www      3535:     }
                   3536:     return 'ok';
1.14      www      3537: }
                   3538: 
1.109     www      3539: # ----------------------------------------------------- Devalidate Spreadsheets
                   3540: 
                   3541: sub devalidate {
1.325     www      3542:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3543:     my $cid=$env{'request.course.id'}; 
1.109     www      3544:     if ($cid) {
1.391     matthew  3545:         # delete the stored spreadsheets for
                   3546:         # - the student level sheet of this user in course's homespace
                   3547:         # - the assessment level sheet for this resource 
                   3548:         #   for this user in user's homespace
1.553     albertel 3549: 	# - current conditional state info
1.325     www      3550: 	my $key=$uname.':'.$udom.':';
1.109     www      3551:         my $status=
1.299     matthew  3552: 	    &del('nohist_calculatedsheets',
1.391     matthew  3553: 		 [$key.'studentcalc:'],
1.620     albertel 3554: 		 $env{'course.'.$cid.'.domain'},
                   3555: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3556: 		.' '.
                   3557: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3558: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3559:         unless ($status eq 'ok ok') {
                   3560:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3561:                     $uname.' at '.$udom.' for '.
1.109     www      3562: 		    $symb.': '.$status);
1.133     albertel 3563:         }
1.553     albertel 3564: 	&delenv('user.state.'.$cid);
1.109     www      3565:     }
                   3566: }
                   3567: 
1.265     albertel 3568: sub get_scalar {
                   3569:     my ($string,$end) = @_;
                   3570:     my $value;
                   3571:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3572: 	$value = $1;
                   3573:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3574: 	$value = $1;
                   3575:     }
                   3576:     return &unescape($value);
                   3577: }
                   3578: 
                   3579: sub array2str {
                   3580:   my (@array) = @_;
                   3581:   my $result=&arrayref2str(\@array);
                   3582:   $result=~s/^__ARRAY_REF__//;
                   3583:   $result=~s/__END_ARRAY_REF__$//;
                   3584:   return $result;
                   3585: }
                   3586: 
1.204     albertel 3587: sub arrayref2str {
                   3588:   my ($arrayref) = @_;
1.265     albertel 3589:   my $result='__ARRAY_REF__';
1.204     albertel 3590:   foreach my $elem (@$arrayref) {
1.265     albertel 3591:     if(ref($elem) eq 'ARRAY') {
                   3592:       $result.=&arrayref2str($elem).'&';
                   3593:     } elsif(ref($elem) eq 'HASH') {
                   3594:       $result.=&hashref2str($elem).'&';
                   3595:     } elsif(ref($elem)) {
                   3596:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3597:     } else {
                   3598:       $result.=&escape($elem).'&';
                   3599:     }
                   3600:   }
                   3601:   $result=~s/\&$//;
1.265     albertel 3602:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3603:   return $result;
                   3604: }
                   3605: 
1.168     albertel 3606: sub hash2str {
1.204     albertel 3607:   my (%hash) = @_;
                   3608:   my $result=&hashref2str(\%hash);
1.265     albertel 3609:   $result=~s/^__HASH_REF__//;
                   3610:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3611:   return $result;
                   3612: }
                   3613: 
                   3614: sub hashref2str {
                   3615:   my ($hashref)=@_;
1.265     albertel 3616:   my $result='__HASH_REF__';
1.800     albertel 3617:   foreach my $key (sort(keys(%$hashref))) {
                   3618:     if (ref($key) eq 'ARRAY') {
                   3619:       $result.=&arrayref2str($key).'=';
                   3620:     } elsif (ref($key) eq 'HASH') {
                   3621:       $result.=&hashref2str($key).'=';
                   3622:     } elsif (ref($key)) {
1.265     albertel 3623:       $result.='=';
1.800     albertel 3624:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3625:     } else {
1.800     albertel 3626: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3627:     }
                   3628: 
1.800     albertel 3629:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3630:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3631:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3632:       $result.=&hashref2str($hashref->{$key}).'&';
                   3633:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3634:        $result.='&';
1.800     albertel 3635:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3636:     } else {
1.800     albertel 3637:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3638:     }
                   3639:   }
1.168     albertel 3640:   $result=~s/\&$//;
1.265     albertel 3641:   $result .= '__END_HASH_REF__';
1.168     albertel 3642:   return $result;
                   3643: }
                   3644: 
                   3645: sub str2hash {
1.265     albertel 3646:     my ($string)=@_;
                   3647:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3648:     return %$hash;
                   3649: }
                   3650: 
                   3651: sub str2hashref {
1.168     albertel 3652:   my ($string) = @_;
1.265     albertel 3653: 
                   3654:   my %hash;
                   3655: 
                   3656:   if($string !~ /^__HASH_REF__/) {
                   3657:       if (! ($string eq '' || !defined($string))) {
                   3658: 	  $hash{'error'}='Not hash reference';
                   3659:       }
                   3660:       return (\%hash, $string);
                   3661:   }
                   3662: 
                   3663:   $string =~ s/^__HASH_REF__//;
                   3664: 
                   3665:   while($string !~ /^__END_HASH_REF__/) {
                   3666:       #key
                   3667:       my $key='';
                   3668:       if($string =~ /^__HASH_REF__/) {
                   3669:           ($key, $string)=&str2hashref($string);
                   3670:           if(defined($key->{'error'})) {
                   3671:               $hash{'error'}='Bad data';
                   3672:               return (\%hash, $string);
                   3673:           }
                   3674:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3675:           ($key, $string)=&str2arrayref($string);
                   3676:           if($key->[0] eq 'Array reference error') {
                   3677:               $hash{'error'}='Bad data';
                   3678:               return (\%hash, $string);
                   3679:           }
                   3680:       } else {
                   3681:           $string =~ s/^(.*?)=//;
1.267     albertel 3682: 	  $key=&unescape($1);
1.265     albertel 3683:       }
                   3684:       $string =~ s/^=//;
                   3685: 
                   3686:       #value
                   3687:       my $value='';
                   3688:       if($string =~ /^__HASH_REF__/) {
                   3689:           ($value, $string)=&str2hashref($string);
                   3690:           if(defined($value->{'error'})) {
                   3691:               $hash{'error'}='Bad data';
                   3692:               return (\%hash, $string);
                   3693:           }
                   3694:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3695:           ($value, $string)=&str2arrayref($string);
                   3696:           if($value->[0] eq 'Array reference error') {
                   3697:               $hash{'error'}='Bad data';
                   3698:               return (\%hash, $string);
                   3699:           }
                   3700:       } else {
                   3701: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3702:       }
                   3703:       $string =~ s/^&//;
                   3704: 
                   3705:       $hash{$key}=$value;
1.204     albertel 3706:   }
1.265     albertel 3707: 
                   3708:   $string =~ s/^__END_HASH_REF__//;
                   3709: 
                   3710:   return (\%hash, $string);
1.204     albertel 3711: }
                   3712: 
                   3713: sub str2array {
1.265     albertel 3714:     my ($string)=@_;
                   3715:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3716:     return @$array;
                   3717: }
                   3718: 
                   3719: sub str2arrayref {
1.204     albertel 3720:   my ($string) = @_;
1.265     albertel 3721:   my @array;
                   3722: 
                   3723:   if($string !~ /^__ARRAY_REF__/) {
                   3724:       if (! ($string eq '' || !defined($string))) {
                   3725: 	  $array[0]='Array reference error';
                   3726:       }
                   3727:       return (\@array, $string);
                   3728:   }
                   3729: 
                   3730:   $string =~ s/^__ARRAY_REF__//;
                   3731: 
                   3732:   while($string !~ /^__END_ARRAY_REF__/) {
                   3733:       my $value='';
                   3734:       if($string =~ /^__HASH_REF__/) {
                   3735:           ($value, $string)=&str2hashref($string);
                   3736:           if(defined($value->{'error'})) {
                   3737:               $array[0] ='Array reference error';
                   3738:               return (\@array, $string);
                   3739:           }
                   3740:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3741:           ($value, $string)=&str2arrayref($string);
                   3742:           if($value->[0] eq 'Array reference error') {
                   3743:               $array[0] ='Array reference error';
                   3744:               return (\@array, $string);
                   3745:           }
                   3746:       } else {
                   3747: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3748:       }
                   3749:       $string =~ s/^&//;
                   3750: 
                   3751:       push(@array, $value);
1.191     harris41 3752:   }
1.265     albertel 3753: 
                   3754:   $string =~ s/^__END_ARRAY_REF__//;
                   3755: 
                   3756:   return (\@array, $string);
1.168     albertel 3757: }
                   3758: 
1.167     albertel 3759: # -------------------------------------------------------------------Temp Store
                   3760: 
1.168     albertel 3761: sub tmpreset {
                   3762:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3763:   if (!$symb) {
                   3764:     $symb=&symbread();
1.620     albertel 3765:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3766:   }
                   3767:   $symb=escape($symb);
                   3768: 
1.620     albertel 3769:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3770:   $namespace=~s/\//\_/g;
                   3771:   $namespace=~s/\W//g;
                   3772: 
1.620     albertel 3773:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3774:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3775:   if ($domain eq 'public' && $stuname eq 'public') {
                   3776:       $stuname=$ENV{'REMOTE_ADDR'};
                   3777:   }
1.168     albertel 3778:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3779:   my %hash;
                   3780:   if (tie(%hash,'GDBM_File',
                   3781: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3782: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3783:     foreach my $key (keys(%hash)) {
1.180     albertel 3784:       if ($key=~ /:$symb/) {
1.168     albertel 3785: 	delete($hash{$key});
                   3786:       }
                   3787:     }
                   3788:   }
                   3789: }
                   3790: 
1.167     albertel 3791: sub tmpstore {
1.168     albertel 3792:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3793: 
                   3794:   if (!$symb) {
                   3795:     $symb=&symbread();
1.620     albertel 3796:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3797:   }
                   3798:   $symb=escape($symb);
                   3799: 
                   3800:   if (!$namespace) {
                   3801:     # I don't think we would ever want to store this for a course.
                   3802:     # it seems this will only be used if we don't have a course.
1.620     albertel 3803:     #$namespace=$env{'request.course.id'};
1.168     albertel 3804:     #if (!$namespace) {
1.620     albertel 3805:       $namespace=$env{'request.state'};
1.168     albertel 3806:     #}
                   3807:   }
                   3808:   $namespace=~s/\//\_/g;
                   3809:   $namespace=~s/\W//g;
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 $now=time;
                   3816:   my %hash;
                   3817:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3818:   if (tie(%hash,'GDBM_File',
                   3819: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3820: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3821:     $hash{"version:$symb"}++;
                   3822:     my $version=$hash{"version:$symb"};
                   3823:     my $allkeys=''; 
                   3824:     foreach my $key (keys(%$storehash)) {
                   3825:       $allkeys.=$key.':';
1.591     albertel 3826:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3827:     }
                   3828:     $hash{"$version:$symb:timestamp"}=$now;
                   3829:     $allkeys.='timestamp';
                   3830:     $hash{"$version:keys:$symb"}=$allkeys;
                   3831:     if (untie(%hash)) {
                   3832:       return 'ok';
                   3833:     } else {
                   3834:       return "error:$!";
                   3835:     }
                   3836:   } else {
                   3837:     return "error:$!";
                   3838:   }
                   3839: }
1.167     albertel 3840: 
1.168     albertel 3841: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3842: 
1.168     albertel 3843: sub tmprestore {
                   3844:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3845: 
1.168     albertel 3846:   if (!$symb) {
                   3847:     $symb=&symbread();
1.620     albertel 3848:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3849:   }
                   3850:   $symb=escape($symb);
                   3851: 
1.620     albertel 3852:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3853: 
1.620     albertel 3854:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3855:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3856:   if ($domain eq 'public' && $stuname eq 'public') {
                   3857:       $stuname=$ENV{'REMOTE_ADDR'};
                   3858:   }
1.168     albertel 3859:   my %returnhash;
                   3860:   $namespace=~s/\//\_/g;
                   3861:   $namespace=~s/\W//g;
                   3862:   my %hash;
                   3863:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3864:   if (tie(%hash,'GDBM_File',
                   3865: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3866: 	  &GDBM_READER(),0640)) {
1.168     albertel 3867:     my $version=$hash{"version:$symb"};
                   3868:     $returnhash{'version'}=$version;
                   3869:     my $scope;
                   3870:     for ($scope=1;$scope<=$version;$scope++) {
                   3871:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3872:       my @keys=split(/:/,$vkeys);
                   3873:       my $key;
                   3874:       $returnhash{"$scope:keys"}=$vkeys;
                   3875:       foreach $key (@keys) {
1.591     albertel 3876: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3877: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3878:       }
                   3879:     }
1.168     albertel 3880:     if (!(untie(%hash))) {
                   3881:       return "error:$!";
                   3882:     }
                   3883:   } else {
                   3884:     return "error:$!";
                   3885:   }
                   3886:   return %returnhash;
1.167     albertel 3887: }
                   3888: 
1.9       www      3889: # ----------------------------------------------------------------------- Store
                   3890: 
                   3891: sub store {
1.124     www      3892:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3893:     my $home='';
                   3894: 
1.168     albertel 3895:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3896: 
1.213     www      3897:     $symb=&symbclean($symb);
1.122     albertel 3898:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3899: 
1.620     albertel 3900:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3901:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3902: 
                   3903:     &devalidate($symb,$stuname,$domain);
1.109     www      3904: 
                   3905:     $symb=escape($symb);
1.187     www      3906:     if (!$namespace) { 
1.620     albertel 3907:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3908:           return ''; 
                   3909:        } 
                   3910:     }
1.620     albertel 3911:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3912: 
                   3913:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3914:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3915: 
1.12      www      3916:     my $namevalue='';
1.800     albertel 3917:     foreach my $key (keys(%$storehash)) {
                   3918:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3919:     }
1.12      www      3920:     $namevalue=~s/\&$//;
1.187     www      3921:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3922:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3923: }
                   3924: 
1.47      www      3925: # -------------------------------------------------------------- Critical Store
                   3926: 
                   3927: sub cstore {
1.124     www      3928:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3929:     my $home='';
                   3930: 
1.168     albertel 3931:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3932: 
1.213     www      3933:     $symb=&symbclean($symb);
1.122     albertel 3934:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3935: 
1.620     albertel 3936:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3937:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3938: 
                   3939:     &devalidate($symb,$stuname,$domain);
1.109     www      3940: 
                   3941:     $symb=escape($symb);
1.187     www      3942:     if (!$namespace) { 
1.620     albertel 3943:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3944:           return ''; 
                   3945:        } 
                   3946:     }
1.620     albertel 3947:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3948: 
                   3949:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3950:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3951: 
1.47      www      3952:     my $namevalue='';
1.800     albertel 3953:     foreach my $key (keys(%$storehash)) {
                   3954:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3955:     }
1.47      www      3956:     $namevalue=~s/\&$//;
1.187     www      3957:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3958:     return critical
                   3959:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3960: }
                   3961: 
1.9       www      3962: # --------------------------------------------------------------------- Restore
                   3963: 
                   3964: sub restore {
1.124     www      3965:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3966:     my $home='';
                   3967: 
1.168     albertel 3968:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3969: 
1.122     albertel 3970:     if (!$symb) {
                   3971:       unless ($symb=escape(&symbread())) { return ''; }
                   3972:     } else {
1.213     www      3973:       $symb=&escape(&symbclean($symb));
1.122     albertel 3974:     }
1.188     www      3975:     if (!$namespace) { 
1.620     albertel 3976:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3977:           return ''; 
                   3978:        } 
                   3979:     }
1.620     albertel 3980:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3981:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3982:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3983:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3984: 
1.12      www      3985:     my %returnhash=();
1.800     albertel 3986:     foreach my $line (split(/\&/,$answer)) {
                   3987: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3988:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3989:     }
1.75      www      3990:     my $version;
                   3991:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3992:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3993:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3994:        }
1.75      www      3995:     }
1.13      www      3996:     return %returnhash;
1.34      www      3997: }
                   3998: 
                   3999: # ---------------------------------------------------------- Course Description
                   4000: 
                   4001: sub coursedescription {
1.731     albertel 4002:     my ($courseid,$args)=@_;
1.34      www      4003:     $courseid=~s/^\///;
1.49      www      4004:     $courseid=~s/\_/\//g;
1.34      www      4005:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4006:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4007:     my $normalid=$cdomain.'_'.$cnum;
                   4008:     # need to always cache even if we get errors otherwise we keep 
                   4009:     # trying and trying and trying to get the course description.
                   4010:     my %envhash=();
                   4011:     my %returnhash=();
1.731     albertel 4012:     
                   4013:     my $expiretime=600;
                   4014:     if ($env{'request.course.id'} eq $normalid) {
                   4015: 	$expiretime=120;
                   4016:     }
                   4017: 
                   4018:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4019:     if (!$args->{'freshen_cache'}
                   4020: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4021: 	foreach my $key (keys(%env)) {
                   4022: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4023: 	    my ($setting) = $1;
                   4024: 	    $returnhash{$setting} = $env{$key};
                   4025: 	}
                   4026: 	return %returnhash;
                   4027:     }
                   4028: 
                   4029:     # get the data agin
                   4030:     if (!$args->{'one_time'}) {
                   4031: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4032:     }
1.811     albertel 4033: 
1.34      www      4034:     if ($chome ne 'no_host') {
1.302     albertel 4035:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4036:        if (!exists($returnhash{'con_lost'})) {
                   4037:            $returnhash{'home'}= $chome;
                   4038: 	   $returnhash{'domain'} = $cdomain;
                   4039: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4040:            if (!defined($returnhash{'type'})) {
                   4041:                $returnhash{'type'} = 'Course';
                   4042:            }
1.130     albertel 4043:            while (my ($name,$value) = each %returnhash) {
1.53      www      4044:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4045:            }
1.270     www      4046:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4047:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4048: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4049:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4050:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4051:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4052:        }
                   4053:     }
1.731     albertel 4054:     if (!$args->{'one_time'}) {
1.949     raeburn  4055: 	&appenv(\%envhash);
1.731     albertel 4056:     }
1.302     albertel 4057:     return %returnhash;
1.461     www      4058: }
                   4059: 
1.1080    raeburn  4060: sub update_released_required {
                   4061:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4062:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4063:         $cid = $env{'request.course.id'};
                   4064:         $cdom = $env{'course.'.$cid.'.domain'};
                   4065:         $cnum = $env{'course.'.$cid.'.num'};
                   4066:         $chome = $env{'course.'.$cid.'.home'};
                   4067:     }
                   4068:     if ($needsrelease) {
                   4069:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4070:         my $needsupdate;
                   4071:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4072:             $needsupdate = 1;
                   4073:         } else {
                   4074:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4075:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4076:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4077:                 $needsupdate = 1;
                   4078:             }
                   4079:         }
                   4080:         if ($needsupdate) {
                   4081:             my %needshash = (
                   4082:                              'internal.releaserequired' => $needsrelease,
                   4083:                             );
                   4084:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4085:             if ($putresult eq 'ok') {
                   4086:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4087:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4088:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4089:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4090:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4091:                 }
                   4092:             }
                   4093:         }
                   4094:     }
                   4095:     return;
                   4096: }
                   4097: 
1.461     www      4098: # -------------------------------------------------See if a user is privileged
                   4099: 
                   4100: sub privileged {
                   4101:     my ($username,$domain)=@_;
                   4102:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4103: 			&homeserver($username,$domain));
1.1033    raeburn  4104:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4105:         ($rolesdump =~ /^error:/)) {
                   4106:         return 0;
                   4107:     }
1.461     www      4108:     my $now=time;
                   4109:     if ($rolesdump ne '') {
1.800     albertel 4110:         foreach my $entry (split(/&/,$rolesdump)) {
                   4111: 	    if ($entry!~/^rolesdef_/) {
                   4112: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4113: 		$area=~s/\_\w\w$//;
                   4114: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4115: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4116: 		    my $active=1;
                   4117: 		    if ($tend) {
                   4118: 			if ($tend<$now) { $active=0; }
                   4119: 		    }
                   4120: 		    if ($tstart) {
                   4121: 			if ($tstart>$now) { $active=0; }
                   4122: 		    }
                   4123: 		    if ($active) { return 1; }
                   4124: 		}
                   4125: 	    }
                   4126: 	}
                   4127:     }
                   4128:     return 0;
1.9       www      4129: }
1.1       albertel 4130: 
1.103     harris41 4131: # -------------------------------------------------------- Get user privileges
1.11      www      4132: 
                   4133: sub rolesinit {
                   4134:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4135:     my $now=time;
                   4136:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4137:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4138:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4139:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4140:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4141:         return \%userroles;
                   4142:     }
1.11      www      4143:     my %allroles=();
1.678     raeburn  4144:     my %allgroups=();   
1.11      www      4145: 
                   4146:     if ($rolesdump ne '') {
1.800     albertel 4147:         foreach my $entry (split(/&/,$rolesdump)) {
                   4148: 	  if ($entry!~/^rolesdef_/) {
                   4149:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4150: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4151:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4152: 	    if ($role=~/^cr/) { 
1.807     albertel 4153: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4154: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4155: 		    ($tend,$tstart)=split('_',$trest);
                   4156: 		} else {
                   4157: 		    $trole=$role;
                   4158: 		}
1.678     raeburn  4159:             } elsif ($role =~ m|^gr/|) {
                   4160:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4161:                 next if ($tstart eq '-1');
1.678     raeburn  4162:                 ($trole,$group_privs) = split(/\//,$trole);
                   4163:                 $group_privs = &unescape($group_privs);
1.587     albertel 4164: 	    } else {
                   4165: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4166: 	    }
1.743     albertel 4167: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4168: 					 $username);
                   4169: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4170:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4171:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4172:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4173: 		my $spec=$trole.'.'.$area;
                   4174: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4175: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4176:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4177:                 } elsif ($trole eq 'gr') {
                   4178:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4179: 		} else {
1.567     raeburn  4180:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4181: 		}
1.12      www      4182:             }
1.662     raeburn  4183:           }
1.191     harris41 4184:         }
1.743     albertel 4185:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4186:         $userroles{'user.adv'}    = $adv;
                   4187: 	$userroles{'user.author'} = $author;
1.620     albertel 4188:         $env{'user.adv'}=$adv;
1.11      www      4189:     }
1.743     albertel 4190:     return \%userroles;  
1.11      www      4191: }
                   4192: 
1.567     raeburn  4193: sub set_arearole {
                   4194:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4195: # log the associated role with the area
                   4196:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4197:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4198: }
                   4199: 
                   4200: sub custom_roleprivs {
                   4201:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4202:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4203:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4204:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4205:         my ($rdummy,$roledef)=
                   4206:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4207:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4208:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4209:             if (defined($syspriv)) {
1.1043    raeburn  4210:                 if ($trest =~ /^$match_community$/) {
                   4211:                     $syspriv =~ s/bre\&S//; 
                   4212:                 }
1.567     raeburn  4213:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4214:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4215:             }
                   4216:             if ($tdomain ne '') {
                   4217:                 if (defined($dompriv)) {
                   4218:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4219:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4220:                 }
                   4221:                 if (($trest ne '') && (defined($coursepriv))) {
                   4222:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4223:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4224:                 }
                   4225:             }
                   4226:         }
                   4227:     }
                   4228: }
                   4229: 
1.678     raeburn  4230: sub group_roleprivs {
                   4231:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4232:     my $access = 1;
                   4233:     my $now = time;
                   4234:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4235:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4236:     if ($access) {
1.811     albertel 4237:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4238:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4239:     }
                   4240: }
1.567     raeburn  4241: 
                   4242: sub standard_roleprivs {
                   4243:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4244:     if (defined($pr{$trole.':s'})) {
                   4245:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4246:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4247:     }
                   4248:     if ($tdomain ne '') {
                   4249:         if (defined($pr{$trole.':d'})) {
                   4250:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4251:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4252:         }
                   4253:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4254:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4255:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4256:         }
                   4257:     }
                   4258: }
                   4259: 
                   4260: sub set_userprivs {
1.1064    raeburn  4261:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4262:     my $author=0;
                   4263:     my $adv=0;
1.678     raeburn  4264:     my %grouproles = ();
                   4265:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4266:         my @groupkeys; 
1.1000    raeburn  4267:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4268:             push(@groupkeys,$role);
                   4269:         }
                   4270:         if (ref($groups_roles) eq 'HASH') {
                   4271:             foreach my $key (keys(%{$groups_roles})) {
                   4272:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4273:                     push(@groupkeys,$key);
                   4274:                 }
                   4275:             }
                   4276:         }
                   4277:         if (@groupkeys > 0) {
                   4278:             foreach my $role (@groupkeys) {
                   4279:                 my ($trole,$area,$sec,$extendedarea);
                   4280:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4281:                     $trole = $1;
                   4282:                     $area = $2;
                   4283:                     $sec = $3;
                   4284:                     $extendedarea = $area.$sec;
                   4285:                     if (exists($$allgroups{$area})) {
                   4286:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4287:                             my $spec = $trole.'.'.$extendedarea;
                   4288:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4289:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4290:                         }
1.678     raeburn  4291:                     }
                   4292:                 }
                   4293:             }
                   4294:         }
                   4295:     }
1.800     albertel 4296:     foreach my $group (keys(%grouproles)) {
                   4297:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4298:     }
1.800     albertel 4299:     foreach my $role (keys(%{$allroles})) {
                   4300:         my %thesepriv;
1.941     raeburn  4301:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4302:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4303:             if ($item ne '') {
                   4304:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4305:                 if ($restrictions eq '') {
                   4306:                     $thesepriv{$privilege}='F';
                   4307:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4308:                     $thesepriv{$privilege}.=$restrictions;
                   4309:                 }
                   4310:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4311:             }
                   4312:         }
                   4313:         my $thesestr='';
1.1104    raeburn  4314:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4315: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4316: 	}
                   4317:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4318:     }
                   4319:     return ($author,$adv);
                   4320: }
                   4321: 
1.994     raeburn  4322: sub role_status {
1.1104    raeburn  4323:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4324:     my @pwhere = ();
                   4325:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4326:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4327:         unless (!defined($$role) || $$role eq '') {
                   4328:             $$where=join('.',@pwhere);
                   4329:             $$trolecode=$$role.'.'.$$where;
                   4330:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4331:             $$tstatus='is';
1.1104    raeburn  4332:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4333:                 $$tstatus='future';
1.1034    raeburn  4334:                 if ($$tstart<$now) {
                   4335:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4336:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4337:                             my (%allroles,%allgroups,$group_privs,
                   4338:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4339:                             my %userroles = (
                   4340:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4341:                             );
1.1064    raeburn  4342:                             @rolecodes = ('cm'); 
1.1002    raeburn  4343:                             my $spec=$$role.'.'.$$where;
                   4344:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4345:                             if ($$role =~ /^cr\//) {
                   4346:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4347:                                 push(@rolecodes,'cr');
1.1002    raeburn  4348:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4349:                                 push(@rolecodes,$$role);
1.1002    raeburn  4350:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4351:                                                     $env{'user.name'});
1.1064    raeburn  4352:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4353:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4354:                                 $group_privs = &unescape($group_privs);
                   4355:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4356:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  4357:                                 &get_groups_roles($tdomain,$trest,
                   4358:                                                   \%course_roles,\@rolecodes,
                   4359:                                                   \%groups_roles);
1.1002    raeburn  4360:                             } else {
1.1064    raeburn  4361:                                 push(@rolecodes,$$role);
1.1002    raeburn  4362:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4363:                             }
1.1064    raeburn  4364:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4365:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4366:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4367:                         }
                   4368:                     }
1.1034    raeburn  4369:                     $$tstatus = 'is';
1.1002    raeburn  4370:                 }
1.994     raeburn  4371:             }
                   4372:             if ($$tend) {
1.1104    raeburn  4373:                 if ($$tend<$update) {
1.994     raeburn  4374:                     $$tstatus='expired';
                   4375:                 } elsif ($$tend<$now) {
                   4376:                     $$tstatus='will_not';
                   4377:                 }
                   4378:             }
                   4379:         }
                   4380:     }
                   4381: }
                   4382: 
1.1104    raeburn  4383: sub get_groups_roles {
                   4384:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4385:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4386:                   (ref($rolecodes) eq 'ARRAY') && 
                   4387:                   (ref($groups_roles) eq 'HASH')); 
                   4388:     if (keys(%{$cdom_courseroles}) > 0) {
                   4389:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4390:         if ($cdom ne '' && $cnum ne '') {
                   4391:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4392:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4393:                     my $crsrole = $1;
                   4394:                     my $crssec = $2;
                   4395:                     if ($crsrole =~ /^cr/) {
                   4396:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4397:                             push(@{$rolecodes},'cr');
                   4398:                         }
                   4399:                     } else {
                   4400:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4401:                             push(@{$rolecodes},$crsrole);
                   4402:                         }
                   4403:                     }
                   4404:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4405:                     if ($crssec ne '') {
                   4406:                         $rolekey .= "/$crssec";
                   4407:                     }
                   4408:                     $rolekey .= './';
                   4409:                     $groups_roles->{$rolekey} = $rolecodes;
                   4410:                 }
                   4411:             }
                   4412:         }
                   4413:     }
                   4414:     return;
                   4415: }
                   4416: 
                   4417: sub delete_env_groupprivs {
                   4418:     my ($where,$courseroles,$possroles) = @_;
                   4419:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4420:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4421:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4422:         %{$courseroles->{$udom}} =
                   4423:             &get_my_roles('','','userroles',['active'],
                   4424:                           $possroles,[$udom],1);
                   4425:     }
                   4426:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4427:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4428:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4429:             my $area = '/'.$cdom.'/'.$cnum;
                   4430:             my $privkey = "user.priv.$crsrole.$area";
                   4431:             if ($crssec ne '') {
                   4432:                 $privkey .= '/'.$crssec;
                   4433:             }
                   4434:             $privkey .= ".$area/$group";
                   4435:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4436:         }
                   4437:     }
                   4438:     return;
                   4439: }
                   4440: 
1.994     raeburn  4441: sub check_adhoc_privs {
1.1104    raeburn  4442:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4443:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4444:     if ($env{$cckey}) {
                   4445:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4446:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4447:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4448:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4449:         }
                   4450:     } else {
1.1088    raeburn  4451:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4452:     }
                   4453: }
                   4454: 
                   4455: sub set_adhoc_privileges {
                   4456: # role can be cc or ca
1.1088    raeburn  4457:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4458:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4459:     my $spec = $role.'.'.$area;
                   4460:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4461:                                   $env{'user.name'});
                   4462:     my %ccrole = ();
                   4463:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4464:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4465:     &appenv(\%userroles,[$role,'cm']);
                   4466:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4467:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4468:         &appenv( {'request.role'        => $spec,
                   4469:                   'request.role.domain' => $dcdom,
                   4470:                   'request.course.sec'  => ''
                   4471:                  }
                   4472:                );
                   4473:         my $tadv=0;
                   4474:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4475:         &appenv({'request.role.adv'    => $tadv});
                   4476:     }
1.994     raeburn  4477: }
                   4478: 
1.12      www      4479: # --------------------------------------------------------------- get interface
                   4480: 
                   4481: sub get {
1.131     albertel 4482:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4483:    my $items='';
1.800     albertel 4484:    foreach my $item (@$storearr) {
                   4485:        $items.=&escape($item).'&';
1.191     harris41 4486:    }
1.12      www      4487:    $items=~s/\&$//;
1.620     albertel 4488:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4489:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4490:    my $uhome=&homeserver($uname,$udomain);
                   4491: 
1.133     albertel 4492:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4493:    my @pairs=split(/\&/,$rep);
1.273     albertel 4494:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4495:      return @pairs;
                   4496:    }
1.15      www      4497:    my %returnhash=();
1.42      www      4498:    my $i=0;
1.800     albertel 4499:    foreach my $item (@$storearr) {
                   4500:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4501:       $i++;
1.191     harris41 4502:    }
1.15      www      4503:    return %returnhash;
1.27      www      4504: }
                   4505: 
                   4506: # --------------------------------------------------------------- del interface
                   4507: 
                   4508: sub del {
1.133     albertel 4509:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4510:    my $items='';
1.800     albertel 4511:    foreach my $item (@$storearr) {
                   4512:        $items.=&escape($item).'&';
1.191     harris41 4513:    }
1.984     neumanie 4514: 
1.27      www      4515:    $items=~s/\&$//;
1.620     albertel 4516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4517:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4518:    my $uhome=&homeserver($uname,$udomain);
                   4519:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4520: }
                   4521: 
                   4522: # -------------------------------------------------------------- dump interface
                   4523: 
                   4524: sub dump {
1.1086    raeburn  4525:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4526:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4527:     if (!$uname) { $uname=$env{'user.name'}; }
                   4528:     my $uhome=&homeserver($uname,$udomain);
                   4529:     if ($regexp) {
                   4530: 	$regexp=&escape($regexp);
                   4531:     } else {
                   4532: 	$regexp='.';
                   4533:     }
1.1086    raeburn  4534:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4535:     my @pairs=split(/\&/,$rep);
                   4536:     my %returnhash=();
1.1098    foxr     4537:     if (!($rep =~ /^error/ )) {
                   4538: 	foreach my $item (@pairs) {
                   4539: 	    my ($key,$value)=split(/=/,$item,2);
                   4540: 	    $key = &unescape($key);
                   4541: 	    next if ($key =~ /^error: 2 /);
                   4542: 	    $returnhash{$key}=&thaw_unescape($value);
                   4543: 	}
1.755     albertel 4544:     }
                   4545:     return %returnhash;
1.407     www      4546: }
                   4547: 
1.1098    foxr     4548: 
1.717     albertel 4549: # --------------------------------------------------------- dumpstore interface
                   4550: 
                   4551: sub dumpstore {
                   4552:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4553:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4554:    if (!$uname) { $uname=$env{'user.name'}; }
                   4555:    my $uhome=&homeserver($uname,$udomain);
                   4556:    if ($regexp) {
                   4557:        $regexp=&escape($regexp);
                   4558:    } else {
                   4559:        $regexp='.';
                   4560:    }
                   4561:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4562:    my @pairs=split(/\&/,$rep);
                   4563:    my %returnhash=();
                   4564:    foreach my $item (@pairs) {
                   4565:        my ($key,$value)=split(/=/,$item,2);
                   4566:        next if ($key =~ /^error: 2 /);
                   4567:        $returnhash{$key}=&thaw_unescape($value);
                   4568:    }
                   4569:    return %returnhash;
1.717     albertel 4570: }
                   4571: 
1.407     www      4572: # -------------------------------------------------------------- keys interface
                   4573: 
                   4574: sub getkeys {
                   4575:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4576:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4577:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4578:    my $uhome=&homeserver($uname,$udomain);
                   4579:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4580:    my @keyarray=();
1.800     albertel 4581:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4582:       next if ($key =~ /^error: 2 /);
1.800     albertel 4583:       push(@keyarray,&unescape($key));
1.407     www      4584:    }
                   4585:    return @keyarray;
1.318     matthew  4586: }
                   4587: 
1.319     matthew  4588: # --------------------------------------------------------------- currentdump
                   4589: sub currentdump {
1.328     matthew  4590:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4591:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4592:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4593:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4594:    my $uhome = &homeserver($sname,$sdom);
                   4595:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4596:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4597:    #
1.318     matthew  4598:    my %returnhash=();
1.319     matthew  4599:    #
                   4600:    if ($rep eq "unknown_cmd") { 
                   4601:        # an old lond will not know currentdump
                   4602:        # Do a dump and make it look like a currentdump
1.822     albertel 4603:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4604:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4605:        my %hash = @tmp;
                   4606:        @tmp=();
1.424     matthew  4607:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4608:    } else {
                   4609:        my @pairs=split(/\&/,$rep);
1.800     albertel 4610:        foreach my $pair (@pairs) {
                   4611:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4612:            my ($symb,$param) = split(/:/,$key);
                   4613:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4614:                                                         &thaw_unescape($value);
1.319     matthew  4615:        }
1.191     harris41 4616:    }
1.12      www      4617:    return %returnhash;
1.424     matthew  4618: }
                   4619: 
                   4620: sub convert_dump_to_currentdump{
                   4621:     my %hash = %{shift()};
                   4622:     my %returnhash;
                   4623:     # Code ripped from lond, essentially.  The only difference
                   4624:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4625:     # we might run in to problems with parameter names =~ /^v\./
                   4626:     while (my ($key,$value) = each(%hash)) {
                   4627:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4628: 	$symb  = &unescape($symb);
                   4629: 	$param = &unescape($param);
1.424     matthew  4630:         next if ($v eq 'version' || $symb eq 'keys');
                   4631:         next if (exists($returnhash{$symb}) &&
                   4632:                  exists($returnhash{$symb}->{$param}) &&
                   4633:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4634:         $returnhash{$symb}->{$param}=$value;
                   4635:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4636:     }
                   4637:     #
                   4638:     # Remove all of the keys in the hashes which keep track of
                   4639:     # the version of the parameter.
                   4640:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4641:         # use a foreach because we are going to delete from the hash.
                   4642:         foreach my $key (keys(%$param_hash)) {
                   4643:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4644:         }
                   4645:     }
                   4646:     return \%returnhash;
1.12      www      4647: }
                   4648: 
1.627     albertel 4649: # ------------------------------------------------------ critical inc interface
                   4650: 
                   4651: sub cinc {
                   4652:     return &inc(@_,'critical');
                   4653: }
                   4654: 
1.449     matthew  4655: # --------------------------------------------------------------- inc interface
                   4656: 
                   4657: sub inc {
1.627     albertel 4658:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4659:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4660:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4661:     my $uhome=&homeserver($uname,$udomain);
                   4662:     my $items='';
                   4663:     if (! ref($store)) {
                   4664:         # got a single value, so use that instead
                   4665:         $items = &escape($store).'=&';
                   4666:     } elsif (ref($store) eq 'SCALAR') {
                   4667:         $items = &escape($$store).'=&';        
                   4668:     } elsif (ref($store) eq 'ARRAY') {
                   4669:         $items = join('=&',map {&escape($_);} @{$store});
                   4670:     } elsif (ref($store) eq 'HASH') {
                   4671:         while (my($key,$value) = each(%{$store})) {
                   4672:             $items.= &escape($key).'='.&escape($value).'&';
                   4673:         }
                   4674:     }
                   4675:     $items=~s/\&$//;
1.627     albertel 4676:     if ($critical) {
                   4677: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4678:     } else {
                   4679: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4680:     }
1.449     matthew  4681: }
                   4682: 
1.12      www      4683: # --------------------------------------------------------------- put interface
                   4684: 
                   4685: sub put {
1.134     albertel 4686:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4687:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4688:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4689:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4690:    my $items='';
1.800     albertel 4691:    foreach my $item (keys(%$storehash)) {
                   4692:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4693:    }
1.12      www      4694:    $items=~s/\&$//;
1.134     albertel 4695:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4696: }
                   4697: 
1.631     albertel 4698: # ------------------------------------------------------------ newput interface
                   4699: 
                   4700: sub newput {
                   4701:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4703:    if (!$uname) { $uname=$env{'user.name'}; }
                   4704:    my $uhome=&homeserver($uname,$udomain);
                   4705:    my $items='';
                   4706:    foreach my $key (keys(%$storehash)) {
                   4707:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4708:    }
                   4709:    $items=~s/\&$//;
                   4710:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4711: }
                   4712: 
                   4713: # ---------------------------------------------------------  putstore interface
                   4714: 
1.524     raeburn  4715: sub putstore {
1.715     albertel 4716:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4717:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4718:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4719:    my $uhome=&homeserver($uname,$udomain);
                   4720:    my $items='';
1.715     albertel 4721:    foreach my $key (keys(%$storehash)) {
                   4722:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4723:    }
1.715     albertel 4724:    $items=~s/\&$//;
1.716     albertel 4725:    my $esc_symb=&escape($symb);
                   4726:    my $esc_v=&escape($version);
1.715     albertel 4727:    my $reply =
1.716     albertel 4728:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4729: 	      $uhome);
                   4730:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4731:        # gfall back to way things use to be done
1.715     albertel 4732:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4733: 			    $uname);
1.524     raeburn  4734:    }
1.715     albertel 4735:    return $reply;
                   4736: }
                   4737: 
                   4738: sub old_putstore {
1.716     albertel 4739:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4740:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4741:     if (!$uname) { $uname=$env{'user.name'}; }
                   4742:     my $uhome=&homeserver($uname,$udomain);
                   4743:     my %newstorehash;
1.800     albertel 4744:     foreach my $item (keys(%$storehash)) {
                   4745: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4746: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4747:     }
                   4748:     my $items='';
                   4749:     my %allitems = ();
1.800     albertel 4750:     foreach my $item (keys(%newstorehash)) {
                   4751: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4752: 	    my $key = $1.':keys:'.$2;
                   4753: 	    $allitems{$key} .= $3.':';
                   4754: 	}
1.800     albertel 4755: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4756:     }
1.800     albertel 4757:     foreach my $item (keys(%allitems)) {
                   4758: 	$allitems{$item} =~ s/\:$//;
                   4759: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4760:     }
                   4761:     $items=~s/\&$//;
                   4762:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4763: }
                   4764: 
1.47      www      4765: # ------------------------------------------------------ critical put interface
                   4766: 
                   4767: sub cput {
1.134     albertel 4768:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4769:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4770:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4771:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4772:    my $items='';
1.800     albertel 4773:    foreach my $item (keys(%$storehash)) {
                   4774:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4775:    }
1.47      www      4776:    $items=~s/\&$//;
1.134     albertel 4777:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4778: }
                   4779: 
                   4780: # -------------------------------------------------------------- eget interface
                   4781: 
                   4782: sub eget {
1.133     albertel 4783:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4784:    my $items='';
1.800     albertel 4785:    foreach my $item (@$storearr) {
                   4786:        $items.=&escape($item).'&';
1.191     harris41 4787:    }
1.12      www      4788:    $items=~s/\&$//;
1.620     albertel 4789:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4790:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4791:    my $uhome=&homeserver($uname,$udomain);
                   4792:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4793:    my @pairs=split(/\&/,$rep);
                   4794:    my %returnhash=();
1.42      www      4795:    my $i=0;
1.800     albertel 4796:    foreach my $item (@$storearr) {
                   4797:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4798:       $i++;
1.191     harris41 4799:    }
1.12      www      4800:    return %returnhash;
                   4801: }
                   4802: 
1.667     albertel 4803: # ------------------------------------------------------------ tmpput interface
                   4804: sub tmpput {
1.802     raeburn  4805:     my ($storehash,$server,$context)=@_;
1.667     albertel 4806:     my $items='';
1.800     albertel 4807:     foreach my $item (keys(%$storehash)) {
                   4808: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4809:     }
                   4810:     $items=~s/\&$//;
1.802     raeburn  4811:     if (defined($context)) {
                   4812:         $items .= ':'.&escape($context);
                   4813:     }
1.667     albertel 4814:     return &reply("tmpput:$items",$server);
                   4815: }
                   4816: 
                   4817: # ------------------------------------------------------------ tmpget interface
                   4818: sub tmpget {
1.688     albertel 4819:     my ($token,$server)=@_;
                   4820:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4821:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4822:     my %returnhash;
                   4823:     foreach my $item (split(/\&/,$rep)) {
                   4824: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4825:         next if ($key =~ /^error: 2 /);
1.667     albertel 4826: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4827:     }
                   4828:     return %returnhash;
                   4829: }
                   4830: 
1.1113    raeburn  4831: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 4832: sub tmpdel {
                   4833:     my ($token,$server)=@_;
                   4834:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4835:     return &reply("tmpdel:$token",$server);
                   4836: }
                   4837: 
1.765     albertel 4838: # -------------------------------------------------- portfolio access checking
                   4839: 
                   4840: sub portfolio_access {
1.766     albertel 4841:     my ($requrl) = @_;
1.765     albertel 4842:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4843:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4844:     if ($result) {
                   4845:         my %setters;
                   4846:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4847:             my ($startblock,$endblock) =
                   4848:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4849:             if ($startblock && $endblock) {
                   4850:                 return 'B';
                   4851:             }
                   4852:         } else {
                   4853:             my ($startblock,$endblock) =
                   4854:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4855:             if ($startblock && $endblock) {
                   4856:                 return 'B';
                   4857:             }
                   4858:         }
                   4859:     }
1.765     albertel 4860:     if ($result eq 'ok') {
1.766     albertel 4861:        return 'F';
1.765     albertel 4862:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4863:        return 'A';
1.765     albertel 4864:     }
1.766     albertel 4865:     return '';
1.765     albertel 4866: }
                   4867: 
                   4868: sub get_portfolio_access {
1.767     albertel 4869:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4870: 
                   4871:     if (!ref($access_hash)) {
                   4872: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4873: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4874: 						   $file_name);
                   4875: 	$access_hash = $access_controls{$file_name};
                   4876:     }
                   4877: 
1.765     albertel 4878:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4879:     my $now = time;
                   4880:     if (ref($access_hash) eq 'HASH') {
                   4881:         foreach my $key (keys(%{$access_hash})) {
                   4882:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4883:             if ($start > $now) {
                   4884:                 next;
                   4885:             }
                   4886:             if ($end && $end<$now) {
                   4887:                 next;
                   4888:             }
                   4889:             if ($scope eq 'public') {
                   4890:                 $public = $key;
                   4891:                 last;
                   4892:             } elsif ($scope eq 'guest') {
                   4893:                 $guest = $key;
                   4894:             } elsif ($scope eq 'domains') {
                   4895:                 push(@domains,$key);
                   4896:             } elsif ($scope eq 'users') {
                   4897:                 push(@users,$key);
                   4898:             } elsif ($scope eq 'course') {
                   4899:                 push(@courses,$key);
                   4900:             } elsif ($scope eq 'group') {
                   4901:                 push(@groups,$key);
                   4902:             }
                   4903:         }
                   4904:         if ($public) {
                   4905:             return 'ok';
                   4906:         }
                   4907:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4908:             if ($guest) {
                   4909:                 return $guest;
                   4910:             }
                   4911:         } else {
                   4912:             if (@domains > 0) {
                   4913:                 foreach my $domkey (@domains) {
                   4914:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4915:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4916:                             return 'ok';
                   4917:                         }
                   4918:                     }
                   4919:                 }
                   4920:             }
                   4921:             if (@users > 0) {
                   4922:                 foreach my $userkey (@users) {
1.865     raeburn  4923:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4924:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4925:                             if (ref($item) eq 'HASH') {
                   4926:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4927:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4928:                                     return 'ok';
                   4929:                                 }
                   4930:                             }
                   4931:                         }
                   4932:                     } 
1.765     albertel 4933:                 }
                   4934:             }
                   4935:             my %roleshash;
                   4936:             my @courses_and_groups = @courses;
                   4937:             push(@courses_and_groups,@groups); 
                   4938:             if (@courses_and_groups > 0) {
                   4939:                 my (%allgroups,%allroles); 
                   4940:                 my ($start,$end,$role,$sec,$group);
                   4941:                 foreach my $envkey (%env) {
1.1060    raeburn  4942:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4943:                         my $cid = $2.'_'.$3; 
                   4944:                         if ($1 eq 'gr') {
                   4945:                             $group = $4;
                   4946:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4947:                         } else {
                   4948:                             if ($4 eq '') {
                   4949:                                 $sec = 'none';
                   4950:                             } else {
                   4951:                                 $sec = $4;
                   4952:                             }
                   4953:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4954:                         }
1.811     albertel 4955:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4956:                         my $cid = $2.'_'.$3;
                   4957:                         if ($4 eq '') {
                   4958:                             $sec = 'none';
                   4959:                         } else {
                   4960:                             $sec = $4;
                   4961:                         }
                   4962:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4963:                     }
                   4964:                 }
                   4965:                 if (keys(%allroles) == 0) {
                   4966:                     return;
                   4967:                 }
                   4968:                 foreach my $key (@courses_and_groups) {
                   4969:                     my %content = %{$$access_hash{$key}};
                   4970:                     my $cnum = $content{'number'};
                   4971:                     my $cdom = $content{'domain'};
                   4972:                     my $cid = $cdom.'_'.$cnum;
                   4973:                     if (!exists($allroles{$cid})) {
                   4974:                         next;
                   4975:                     }    
                   4976:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4977:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4978:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4979:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4980:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4981:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4982:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4983:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4984:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4985:                                         if (grep/^all$/,@sections) {
                   4986:                                             return 'ok';
                   4987:                                         } else {
                   4988:                                             if (grep/^$sec$/,@sections) {
                   4989:                                                 return 'ok';
                   4990:                                             }
                   4991:                                         }
                   4992:                                     }
                   4993:                                 }
                   4994:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4995:                                     if (grep/^none$/,@groups) {
                   4996:                                         return 'ok';
                   4997:                                     }
                   4998:                                 } else {
                   4999:                                     if (grep/^all$/,@groups) {
                   5000:                                         return 'ok';
                   5001:                                     } 
                   5002:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5003:                                         if (grep/^$group$/,@groups) {
                   5004:                                             return 'ok';
                   5005:                                         }
                   5006:                                     }
                   5007:                                 } 
                   5008:                             }
                   5009:                         }
                   5010:                     }
                   5011:                 }
                   5012:             }
                   5013:             if ($guest) {
                   5014:                 return $guest;
                   5015:             }
                   5016:         }
                   5017:     }
                   5018:     return;
                   5019: }
                   5020: 
                   5021: sub course_group_datechecker {
                   5022:     my ($dates,$now,$status) = @_;
                   5023:     my ($start,$end) = split(/\./,$dates);
                   5024:     if (!$start && !$end) {
                   5025:         return 'ok';
                   5026:     }
                   5027:     if (grep/^active$/,@{$status}) {
                   5028:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5029:             return 'ok';
                   5030:         }
                   5031:     }
                   5032:     if (grep/^previous$/,@{$status}) {
                   5033:         if ($end > $now ) {
                   5034:             return 'ok';
                   5035:         }
                   5036:     }
                   5037:     if (grep/^future$/,@{$status}) {
                   5038:         if ($start > $now) {
                   5039:             return 'ok';
                   5040:         }
                   5041:     }
                   5042:     return; 
                   5043: }
                   5044: 
                   5045: sub parse_portfolio_url {
                   5046:     my ($url) = @_;
                   5047: 
                   5048:     my ($type,$udom,$unum,$group,$file_name);
                   5049:     
1.823     albertel 5050:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5051: 	$type = 1;
                   5052:         $udom = $1;
                   5053:         $unum = $2;
                   5054:         $file_name = $3;
1.823     albertel 5055:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5056: 	$type = 2;
                   5057:         $udom = $1;
                   5058:         $unum = $2;
                   5059:         $group = $3;
                   5060:         $file_name = $3.'/'.$4;
                   5061:     }
                   5062:     if (wantarray) {
                   5063: 	return ($type,$udom,$unum,$file_name,$group);
                   5064:     }
                   5065:     return $type;
                   5066: }
                   5067: 
                   5068: sub is_portfolio_url {
                   5069:     my ($url) = @_;
                   5070:     return scalar(&parse_portfolio_url($url));
                   5071: }
                   5072: 
1.798     raeburn  5073: sub is_portfolio_file {
                   5074:     my ($file) = @_;
1.820     raeburn  5075:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5076:         return 1;
                   5077:     }
                   5078:     return;
                   5079: }
                   5080: 
1.976     raeburn  5081: sub usertools_access {
1.1084    raeburn  5082:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5083:     my ($access,%tools);
                   5084:     if ($context eq '') {
                   5085:         $context = 'tools';
                   5086:     }
                   5087:     if ($context eq 'requestcourses') {
                   5088:         %tools = (
                   5089:                       official   => 1,
                   5090:                       unofficial => 1,
1.1006    raeburn  5091:                       community  => 1,
1.985     raeburn  5092:                  );
                   5093:     } else {
                   5094:         %tools = (
                   5095:                       aboutme   => 1,
                   5096:                       blog      => 1,
                   5097:                       portfolio => 1,
                   5098:                  );
                   5099:     }
1.976     raeburn  5100:     return if (!defined($tools{$tool}));
                   5101: 
                   5102:     if ((!defined($udom)) || (!defined($uname))) {
                   5103:         $udom = $env{'user.domain'};
                   5104:         $uname = $env{'user.name'};
                   5105:     }
                   5106: 
1.978     raeburn  5107:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5108:         if ($action ne 'reload') {
1.985     raeburn  5109:             if ($context eq 'requestcourses') {
                   5110:                 return $env{'environment.canrequest.'.$tool};
                   5111:             } else {
                   5112:                 return $env{'environment.availabletools.'.$tool};
                   5113:             }
                   5114:         }
1.976     raeburn  5115:     }
                   5116: 
                   5117:     my ($toolstatus,$inststatus);
                   5118: 
1.985     raeburn  5119:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5120:          ($action ne 'reload')) {
                   5121:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5122:         $inststatus = $env{'environment.inststatus'};
                   5123:     } else {
1.1084    raeburn  5124:         if (ref($userenvref) eq 'HASH') {
                   5125:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5126:             $inststatus = $userenvref->{'inststatus'};
                   5127:         } else {
                   5128:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5129:             $toolstatus = $userenv{$context.'.'.$tool};
                   5130:             $inststatus = $userenv{'inststatus'};
                   5131:         }
1.976     raeburn  5132:     }
                   5133: 
                   5134:     if ($toolstatus ne '') {
                   5135:         if ($toolstatus) {
                   5136:             $access = 1;
                   5137:         } else {
                   5138:             $access = 0;
                   5139:         }
                   5140:         return $access;
                   5141:     }
                   5142: 
1.1084    raeburn  5143:     my ($is_adv,%domdef);
                   5144:     if (ref($is_advref) eq 'HASH') {
                   5145:         $is_adv = $is_advref->{'is_adv'};
                   5146:     } else {
                   5147:         $is_adv = &is_advanced_user($udom,$uname);
                   5148:     }
                   5149:     if (ref($domdefref) eq 'HASH') {
                   5150:         %domdef = %{$domdefref};
                   5151:     } else {
                   5152:         %domdef = &get_domain_defaults($udom);
                   5153:     }
1.976     raeburn  5154:     if (ref($domdef{$tool}) eq 'HASH') {
                   5155:         if ($is_adv) {
                   5156:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5157:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5158:                     $access = 1;
                   5159:                 } else {
                   5160:                     $access = 0;
                   5161:                 }
                   5162:                 return $access;
                   5163:             }
                   5164:         }
                   5165:         if ($inststatus ne '') {
                   5166:             my ($hasaccess,$hasnoaccess);
                   5167:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5168:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5169:                     if ($domdef{$tool}{$affiliation}) {
                   5170:                         $hasaccess = 1;
                   5171:                     } else {
                   5172:                         $hasnoaccess = 1;
                   5173:                     }
                   5174:                 }
                   5175:             }
                   5176:             if ($hasaccess || $hasnoaccess) {
                   5177:                 if ($hasaccess) {
                   5178:                     $access = 1;
                   5179:                 } elsif ($hasnoaccess) {
                   5180:                     $access = 0; 
                   5181:                 }
                   5182:                 return $access;
                   5183:             }
                   5184:         } else {
                   5185:             if ($domdef{$tool}{'default'} ne '') {
                   5186:                 if ($domdef{$tool}{'default'}) {
                   5187:                     $access = 1;
                   5188:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5189:                     $access = 0;
                   5190:                 }
                   5191:                 return $access;
                   5192:             }
                   5193:         }
                   5194:     } else {
1.985     raeburn  5195:         if ($context eq 'tools') {
                   5196:             $access = 1;
                   5197:         } else {
                   5198:             $access = 0;
                   5199:         }
1.976     raeburn  5200:         return $access;
                   5201:     }
                   5202: }
                   5203: 
1.1050    raeburn  5204: sub is_course_owner {
                   5205:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5206:     if (($udom eq '') || ($uname eq '')) {
                   5207:         $udom = $env{'user.domain'};
                   5208:         $uname = $env{'user.name'};
                   5209:     }
                   5210:     unless (($udom eq '') || ($uname eq '')) {
                   5211:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5212:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5213:                 return 1;
                   5214:             } else {
                   5215:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5216:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5217:                     return 1;
                   5218:                 }
                   5219:             }
                   5220:         }
                   5221:     }
                   5222:     return;
                   5223: }
                   5224: 
1.976     raeburn  5225: sub is_advanced_user {
                   5226:     my ($udom,$uname) = @_;
1.1085    raeburn  5227:     if ($udom ne '' && $uname ne '') {
                   5228:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5229:             return $env{'user.adv'};  
                   5230:         }
                   5231:     }
1.976     raeburn  5232:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5233:     my %allroles;
                   5234:     my $is_adv;
                   5235:     foreach my $role (keys(%roleshash)) {
                   5236:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5237:         my $area = '/'.$tdomain.'/'.$trest;
                   5238:         if ($sec ne '') {
                   5239:             $area .= '/'.$sec;
                   5240:         }
                   5241:         if (($area ne '') && ($trole ne '')) {
                   5242:             my $spec=$trole.'.'.$area;
                   5243:             if ($trole =~ /^cr\//) {
                   5244:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5245:             } elsif ($trole ne 'gr') {
                   5246:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5247:             }
                   5248:         }
                   5249:     }
                   5250:     foreach my $role (keys(%allroles)) {
                   5251:         last if ($is_adv);
                   5252:         foreach my $item (split(/:/,$allroles{$role})) {
                   5253:             if ($item ne '') {
                   5254:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5255:                 if ($privilege eq 'adv') {
                   5256:                     $is_adv = 1;
                   5257:                     last;
                   5258:                 }
                   5259:             }
                   5260:         }
                   5261:     }
                   5262:     return $is_adv;
                   5263: }
1.798     raeburn  5264: 
1.1035    raeburn  5265: sub check_can_request {
1.1036    raeburn  5266:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5267:     my $canreq = 0;
                   5268:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5269:     my @options = ('approval','validate','autolimit');
                   5270:     my $optregex = join('|',@options);
                   5271:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5272:         foreach my $type (@{$types}) {
                   5273:             if (&usertools_access($env{'user.name'},
                   5274:                                   $env{'user.domain'},
                   5275:                                   $type,undef,'requestcourses')) {
                   5276:                 $canreq ++;
1.1036    raeburn  5277:                 if (ref($request_domains) eq 'HASH') {
                   5278:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5279:                 }
1.1035    raeburn  5280:                 if ($dom eq $env{'user.domain'}) {
                   5281:                     $can_request->{$type} = 1;
                   5282:                 }
                   5283:             }
                   5284:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5285:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5286:                 if (@curr > 0) {
1.1036    raeburn  5287:                     foreach my $item (@curr) {
                   5288:                         if (ref($request_domains) eq 'HASH') {
                   5289:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5290:                             if ($otherdom ne '') {
                   5291:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5292:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5293:                                         push(@{$request_domains->{$type}},$otherdom);
                   5294:                                     }
                   5295:                                 } else {
                   5296:                                     push(@{$request_domains->{$type}},$otherdom);
                   5297:                                 }
                   5298:                             }
                   5299:                         }
                   5300:                     }
                   5301:                     unless($dom eq $env{'user.domain'}) {
                   5302:                         $canreq ++;
1.1035    raeburn  5303:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5304:                             $can_request->{$type} = 1;
                   5305:                         }
                   5306:                     }
                   5307:                 }
                   5308:             }
                   5309:         }
                   5310:     }
                   5311:     return $canreq;
                   5312: }
                   5313: 
1.341     www      5314: # ---------------------------------------------- Custom access rule evaluation
                   5315: 
                   5316: sub customaccess {
                   5317:     my ($priv,$uri)=@_;
1.807     albertel 5318:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5319:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5320:     $udom = &LONCAPA::clean_domain($udom);
                   5321:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5322:     my $access=0;
1.800     albertel 5323:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5324: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5325: 	if ($type eq 'user') {
                   5326: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5327: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5328: 		if ($tdom) {
                   5329: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5330: 		}
1.896     albertel 5331: 		if ($tuname) {
                   5332: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5333: 		}
                   5334: 		$access=($effect eq 'allow');
                   5335: 		last;
                   5336: 	    }
                   5337: 	} else {
                   5338: 	    if ($role) {
                   5339: 		if ($role ne $urole) { next; }
                   5340: 	    }
                   5341: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5342: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5343: 		if ($tdom) {
                   5344: 		    if ($tdom ne $udom) { next; }
                   5345: 		}
                   5346: 		if ($tcrs) {
                   5347: 		    if ($tcrs ne $ucrs) { next; }
                   5348: 		}
                   5349: 		if ($tsec) {
                   5350: 		    if ($tsec ne $usec) { next; }
                   5351: 		}
                   5352: 		$access=($effect eq 'allow');
                   5353: 		last;
                   5354: 	    }
                   5355: 	    if ($realm eq '' && $role eq '') {
                   5356: 		$access=($effect eq 'allow');
                   5357: 	    }
1.402     bowersj2 5358: 	}
1.341     www      5359:     }
                   5360:     return $access;
                   5361: }
                   5362: 
1.103     harris41 5363: # ------------------------------------------------- Check for a user privilege
1.12      www      5364: 
                   5365: sub allowed {
1.810     raeburn  5366:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5367:     my $ver_orguri=$uri;
1.439     www      5368:     $uri=&deversion($uri);
1.152     www      5369:     my $orguri=$uri;
1.52      www      5370:     $uri=&declutter($uri);
1.809     raeburn  5371: 
1.810     raeburn  5372:     if ($priv eq 'evb') {
                   5373: # Evade communication block restrictions for specified role in a course
                   5374:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5375:             return $1;
                   5376:         } else {
                   5377:             return;
                   5378:         }
                   5379:     }
                   5380: 
1.620     albertel 5381:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5382: # Free bre access to adm and meta resources
1.775     albertel 5383:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5384: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5385: 	&& ($priv eq 'bre')) {
1.14      www      5386: 	return 'F';
1.159     www      5387:     }
                   5388: 
1.545     banghart 5389: # Free bre access to user's own portfolio contents
1.714     raeburn  5390:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5391:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5392: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5393:         my %setters;
                   5394:         my ($startblock,$endblock) = 
                   5395:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5396:         if ($startblock && $endblock) {
                   5397:             return 'B';
                   5398:         } else {
                   5399:             return 'F';
                   5400:         }
1.545     banghart 5401:     }
                   5402: 
1.762     raeburn  5403: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5404:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5405:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5406:         if (exists($env{'request.course.id'})) {
                   5407:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5408:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5409:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5410:                 my $courseprivid=$env{'request.course.id'};
                   5411:                 $courseprivid=~s/\_/\//;
                   5412:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5413:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5414:                     return $1; 
1.762     raeburn  5415:                 } else {
                   5416:                     if ($env{'request.course.sec'}) {
                   5417:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5418:                     }
                   5419:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5420:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5421:                         return $2;
                   5422:                     }
1.714     raeburn  5423:                 }
                   5424:             }
                   5425:         }
                   5426:     }
                   5427: 
1.159     www      5428: # Free bre to public access
                   5429: 
                   5430:     if ($priv eq 'bre') {
1.238     www      5431:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5432: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5433:            return 'F'; 
                   5434:         }
1.238     www      5435:         if ($copyright eq 'priv') {
                   5436:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5437: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5438: 		return '';
                   5439:             }
                   5440:         }
                   5441:         if ($copyright eq 'domain') {
                   5442:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5443: 	    unless (($env{'user.domain'} eq $1) ||
                   5444:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5445: 		return '';
                   5446:             }
1.262     matthew  5447:         }
1.620     albertel 5448:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5449:             # Library role, so allow browsing of resources in this domain.
                   5450:             return 'F';
1.238     www      5451:         }
1.341     www      5452:         if ($copyright eq 'custom') {
                   5453: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5454:         }
1.14      www      5455:     }
1.264     matthew  5456:     # Domain coordinator is trying to create a course
1.620     albertel 5457:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5458:         # uri is the requested domain in this case.
                   5459:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5460:         # a role of dc for the domain in question.
1.620     albertel 5461:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5462:     }
1.29      www      5463: 
1.52      www      5464:     my $thisallowed='';
                   5465:     my $statecond=0;
                   5466:     my $courseprivid='';
                   5467: 
1.1039    raeburn  5468:     my $ownaccess;
1.1043    raeburn  5469:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5470:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5471:         if ($uri eq '') {
                   5472:             $ownaccess = 1;
                   5473:         } else {
                   5474:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5475:                 my $udom = $env{'user.domain'};
                   5476:                 my $uname = $env{'user.name'};
                   5477:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5478:                     $ownaccess = 1;
1.1040    raeburn  5479:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5480:                     unless ($uri =~ m{\.\./}) {
                   5481:                         $ownaccess = 1;
                   5482:                     }
                   5483:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5484:                     my $now = time;
                   5485:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5486:                         my $adom = $1;
                   5487:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5488:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5489:                                 my ($start,$end) = split('.',$env{$key});
                   5490:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5491:                                     $ownaccess = 1;
                   5492:                                     last;
                   5493:                                 }
                   5494:                             }
                   5495:                         }
                   5496:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5497:                         my $adom = $1;
                   5498:                         my $aname = $2;
1.1042    raeburn  5499:                         foreach my $role ('ca','aa') { 
                   5500:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5501:                                 my ($start,$end) =
                   5502:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5503:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5504:                                     $ownaccess = 1;
                   5505:                                     last;
                   5506:                                 }
1.1039    raeburn  5507:                             }
                   5508:                         }
                   5509:                     }
                   5510:                 }
                   5511:             }
                   5512:         }
                   5513:     }
                   5514: 
1.52      www      5515: # Course
                   5516: 
1.620     albertel 5517:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5518:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5519:             $thisallowed.=$1;
                   5520:         }
1.52      www      5521:     }
1.29      www      5522: 
1.52      www      5523: # Domain
                   5524: 
1.620     albertel 5525:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5526:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5527:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5528:             $thisallowed.=$1;
                   5529:         }
1.12      www      5530:     }
1.52      www      5531: 
                   5532: # Course: uri itself is a course
1.66      www      5533:     my $courseuri=$uri;
                   5534:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5535:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5536: 
1.620     albertel 5537:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5538:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5539:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5540:             $thisallowed.=$1;
                   5541:         }
1.12      www      5542:     }
1.29      www      5543: 
1.665     albertel 5544: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5545: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5546:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5547: 	$thisallowed='';
1.671     raeburn  5548:         my ($match)=&is_on_map($uri);
                   5549:         if ($match) {
                   5550:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5551:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5552:                 $thisallowed.=$1;
                   5553:             }
                   5554:         } else {
1.705     albertel 5555:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5556:             if ($refuri) {
                   5557:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5558:                     $thisallowed='F';
1.671     raeburn  5559:                 } else {
                   5560:                     $refuri=&declutter($refuri);
                   5561:                     my ($match) = &is_on_map($refuri);
                   5562:                     if ($match) {
                   5563:                         $thisallowed='F';
                   5564:                     }
1.669     raeburn  5565:                 }
1.671     raeburn  5566:             }
                   5567:         }
1.314     www      5568:     }
1.492     albertel 5569: 
1.766     albertel 5570:     if ($priv eq 'bre'
                   5571: 	&& $thisallowed ne 'F' 
                   5572: 	&& $thisallowed ne '2'
                   5573: 	&& &is_portfolio_url($uri)) {
                   5574: 	$thisallowed = &portfolio_access($uri);
                   5575:     }
                   5576:     
1.52      www      5577: # Full access at system, domain or course-wide level? Exit.
1.29      www      5578:     if ($thisallowed=~/F/) {
                   5579: 	return 'F';
                   5580:     }
                   5581: 
1.52      www      5582: # If this is generating or modifying users, exit with special codes
1.29      www      5583: 
1.643     www      5584:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5585: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5586: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5587: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5588: 	    unless ($auname) { return $thisallowed; }
                   5589: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5590: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5591: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5592: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5593: 	}
1.52      www      5594: 	return $thisallowed;
                   5595:     }
                   5596: #
1.103     harris41 5597: # Gathered so far: system, domain and course wide privileges
1.52      www      5598: #
                   5599: # Course: See if uri or referer is an individual resource that is part of 
                   5600: # the course
                   5601: 
1.620     albertel 5602:     if ($env{'request.course.id'}) {
1.232     www      5603: 
1.620     albertel 5604:        $courseprivid=$env{'request.course.id'};
                   5605:        if ($env{'request.course.sec'}) {
                   5606:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5607:        }
                   5608:        $courseprivid=~s/\_/\//;
                   5609:        my $checkreferer=1;
1.232     www      5610:        my ($match,$cond)=&is_on_map($uri);
                   5611:        if ($match) {
                   5612:            $statecond=$cond;
1.620     albertel 5613:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5614:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5615:                $thisallowed.=$1;
                   5616:                $checkreferer=0;
                   5617:            }
1.29      www      5618:        }
1.83      www      5619:        
1.148     www      5620:        if ($checkreferer) {
1.620     albertel 5621: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5622:             unless ($refuri) {
1.800     albertel 5623:                 foreach my $key (keys(%env)) {
                   5624: 		    if ($key=~/^httpref\..*\*/) {
                   5625: 			my $pattern=$key;
1.156     www      5626:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5627:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5628:                         $pattern=~s/\//\\\//g;
1.152     www      5629:                         if ($orguri=~/$pattern/) {
1.800     albertel 5630: 			    $refuri=$env{$key};
1.148     www      5631:                         }
                   5632:                     }
1.191     harris41 5633:                 }
1.148     www      5634:             }
1.232     www      5635: 
1.148     www      5636:          if ($refuri) { 
1.152     www      5637: 	  $refuri=&declutter($refuri);
1.232     www      5638:           my ($match,$cond)=&is_on_map($refuri);
                   5639:             if ($match) {
                   5640:               my $refstatecond=$cond;
1.620     albertel 5641:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5642:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5643:                   $thisallowed.=$1;
1.53      www      5644:                   $uri=$refuri;
                   5645:                   $statecond=$refstatecond;
1.52      www      5646:               }
                   5647:           }
1.148     www      5648:         }
1.29      www      5649:        }
1.52      www      5650:    }
1.29      www      5651: 
1.52      www      5652: #
1.103     harris41 5653: # Gathered now: all privileges that could apply, and condition number
1.52      www      5654: # 
                   5655: #
                   5656: # Full or no access?
                   5657: #
1.29      www      5658: 
1.52      www      5659:     if ($thisallowed=~/F/) {
                   5660: 	return 'F';
                   5661:     }
1.29      www      5662: 
1.52      www      5663:     unless ($thisallowed) {
                   5664:         return '';
                   5665:     }
1.29      www      5666: 
1.52      www      5667: # Restrictions exist, deal with them
                   5668: #
                   5669: #   C:according to course preferences
                   5670: #   R:according to resource settings
                   5671: #   L:unless locked
                   5672: #   X:according to user session state
                   5673: #
                   5674: 
                   5675: # Possibly locked functionality, check all courses
1.54      www      5676: # Locks might take effect only after 10 minutes cache expiration for other
                   5677: # courses, and 2 minutes for current course
1.52      www      5678: 
                   5679:     my $envkey;
                   5680:     if ($thisallowed=~/L/) {
1.1000    raeburn  5681:         foreach $envkey (keys(%env)) {
1.54      www      5682:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5683:                my $courseid=$2;
                   5684:                my $roleid=$1.'.'.$2;
1.92      www      5685:                $courseid=~s/^\///;
1.54      www      5686:                my $expiretime=600;
1.620     albertel 5687:                if ($env{'request.role'} eq $roleid) {
1.54      www      5688: 		  $expiretime=120;
                   5689:                }
                   5690: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5691:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5692:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5693: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5694:                }
1.620     albertel 5695:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5696:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5697: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5698:                        &log($env{'user.domain'},$env{'user.name'},
                   5699:                             $env{'user.home'},
1.57      www      5700:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5701:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5702:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5703: 		       return '';
                   5704:                    }
                   5705:                }
1.620     albertel 5706:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5707:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5708: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5709:                        &log($env{'user.domain'},$env{'user.name'},
                   5710:                             $env{'user.home'},
1.57      www      5711:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5712:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5713:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5714: 		       return '';
                   5715:                    }
                   5716:                }
                   5717: 	   }
1.29      www      5718:        }
1.52      www      5719:     }
                   5720:    
                   5721: #
                   5722: # Rest of the restrictions depend on selected course
                   5723: #
                   5724: 
1.620     albertel 5725:     unless ($env{'request.course.id'}) {
1.766     albertel 5726: 	if ($thisallowed eq 'A') {
                   5727: 	    return 'A';
1.814     raeburn  5728:         } elsif ($thisallowed eq 'B') {
                   5729:             return 'B';
1.766     albertel 5730: 	} else {
                   5731: 	    return '1';
                   5732: 	}
1.52      www      5733:     }
1.29      www      5734: 
1.52      www      5735: #
                   5736: # Now user is definitely in a course
                   5737: #
1.53      www      5738: 
                   5739: 
                   5740: # Course preferences
                   5741: 
                   5742:    if ($thisallowed=~/C/) {
1.620     albertel 5743:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5744:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5745:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5746: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  5747: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5748: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5749: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5750: 			$env{'request.course.id'});
                   5751: 	   }
1.237     www      5752:            return '';
                   5753:        }
                   5754: 
1.620     albertel 5755:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5756: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  5757: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5758: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5759: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5760: 			$env{'request.course.id'});
                   5761: 	   }
1.54      www      5762:            return '';
                   5763:        }
1.53      www      5764:    }
                   5765: 
                   5766: # Resource preferences
                   5767: 
                   5768:    if ($thisallowed=~/R/) {
1.620     albertel 5769:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5770:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  5771: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 5772: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5773: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5774: 	   }
                   5775: 	   return '';
1.54      www      5776:        }
1.53      www      5777:    }
1.30      www      5778: 
1.246     www      5779: # Restricted by state or randomout?
1.30      www      5780: 
1.52      www      5781:    if ($thisallowed=~/X/) {
1.620     albertel 5782:       if ($env{'acc.randomout'}) {
1.579     albertel 5783: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5784:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5785:             return ''; 
                   5786:          }
1.247     www      5787:       }
                   5788:       if (&condval($statecond)) {
1.52      www      5789: 	 return '2';
                   5790:       } else {
                   5791:          return '';
                   5792:       }
                   5793:    }
1.30      www      5794: 
1.766     albertel 5795:     if ($thisallowed eq 'A') {
                   5796: 	return 'A';
1.814     raeburn  5797:     } elsif ($thisallowed eq 'B') {
                   5798:         return 'B';
1.766     albertel 5799:     }
1.52      www      5800:    return 'F';
1.232     www      5801: }
                   5802: 
1.710     albertel 5803: sub split_uri_for_cond {
                   5804:     my $uri=&deversion(&declutter(shift));
                   5805:     my @uriparts=split(/\//,$uri);
                   5806:     my $filename=pop(@uriparts);
                   5807:     my $pathname=join('/',@uriparts);
                   5808:     return ($pathname,$filename);
                   5809: }
1.232     www      5810: # --------------------------------------------------- Is a resource on the map?
                   5811: 
                   5812: sub is_on_map {
1.710     albertel 5813:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5814:     #Trying to find the conditional for the file
1.620     albertel 5815:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5816: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5817:     if ($match) {
1.289     bowersj2 5818: 	return (1,$1);
                   5819:     } else {
1.434     www      5820: 	return (0,0);
1.289     bowersj2 5821:     }
1.12      www      5822: }
                   5823: 
1.427     www      5824: # --------------------------------------------------------- Get symb from alias
                   5825: 
                   5826: sub get_symb_from_alias {
                   5827:     my $symb=shift;
                   5828:     my ($map,$resid,$url)=&decode_symb($symb);
                   5829: # Already is a symb
                   5830:     if ($url) { return $symb; }
                   5831: # Must be an alias
                   5832:     my $aliassymb='';
                   5833:     my %bighash;
1.620     albertel 5834:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5835:                             &GDBM_READER(),0640)) {
                   5836:         my $rid=$bighash{'mapalias_'.$symb};
                   5837: 	if ($rid) {
                   5838: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5839: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5840: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5841: 	}
                   5842:         untie %bighash;
                   5843:     }
                   5844:     return $aliassymb;
                   5845: }
                   5846: 
1.12      www      5847: # ----------------------------------------------------------------- Define Role
                   5848: 
                   5849: sub definerole {
                   5850:   if (allowed('mcr','/')) {
                   5851:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5852:     foreach my $role (split(':',$sysrole)) {
                   5853: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5854:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5855:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5856: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5857:                return "refused:s:$crole&$cqual"; 
                   5858:             }
                   5859:         }
1.191     harris41 5860:     }
1.800     albertel 5861:     foreach my $role (split(':',$domrole)) {
                   5862: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5863:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5864:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5865: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5866:                return "refused:d:$crole&$cqual"; 
                   5867:             }
                   5868:         }
1.191     harris41 5869:     }
1.800     albertel 5870:     foreach my $role (split(':',$courole)) {
                   5871: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5872:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5873:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5874: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5875:                return "refused:c:$crole&$cqual"; 
                   5876:             }
                   5877:         }
1.191     harris41 5878:     }
1.620     albertel 5879:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5880:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5881: 	        "rolesdef_$rolename=".
                   5882:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5883:     return reply($command,$env{'user.home'});
1.12      www      5884:   } else {
                   5885:     return 'refused';
                   5886:   }
1.105     harris41 5887: }
                   5888: 
                   5889: # ---------------- Make a metadata query against the network of library servers
                   5890: 
                   5891: sub metadata_query {
1.244     matthew  5892:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5893:     my %rhash;
1.845     albertel 5894:     my %libserv = &all_library();
1.244     matthew  5895:     my @server_list = (defined($server_array) ? @$server_array
                   5896:                                               : keys(%libserv) );
                   5897:     for my $server (@server_list) {
1.118     harris41 5898: 	unless ($custom or $customshow) {
                   5899: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5900: 	    $rhash{$server}=$reply;
                   5901: 	}
                   5902: 	else {
                   5903: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5904: 			     &escape($custom).':'.&escape($customshow),
                   5905: 			     $server);
                   5906: 	    $rhash{$server}=$reply;
                   5907: 	}
1.112     harris41 5908:     }
1.118     harris41 5909:     return \%rhash;
1.240     www      5910: }
                   5911: 
                   5912: # ----------------------------------------- Send log queries and wait for reply
                   5913: 
                   5914: sub log_query {
                   5915:     my ($uname,$udom,$query,%filters)=@_;
                   5916:     my $uhome=&homeserver($uname,$udom);
                   5917:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5918:     my $uhost=&hostname($uhome);
1.800     albertel 5919:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5920:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5921:                        $uhome);
1.479     albertel 5922:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5923:     return get_query_reply($queryid);
                   5924: }
                   5925: 
1.818     raeburn  5926: # -------------------------- Update MySQL table for portfolio file
                   5927: 
                   5928: sub update_portfolio_table {
1.821     raeburn  5929:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5930:     if ($group ne '') {
                   5931:         $file_name =~s /^\Q$group\E//;
                   5932:     }
1.818     raeburn  5933:     my $homeserver = &homeserver($uname,$udom);
                   5934:     my $queryid=
1.821     raeburn  5935:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5936:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5937:     my $reply = &get_query_reply($queryid);
                   5938:     return $reply;
                   5939: }
                   5940: 
1.899     raeburn  5941: # -------------------------- Update MySQL allusers table
                   5942: 
                   5943: sub update_allusers_table {
                   5944:     my ($uname,$udom,$names) = @_;
                   5945:     my $homeserver = &homeserver($uname,$udom);
                   5946:     my $queryid=
                   5947:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5948:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5949:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5950:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5951:                'generation='.&escape($names->{'generation'}).'%%'.
                   5952:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5953:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  5954:     return;
1.899     raeburn  5955: }
                   5956: 
1.508     raeburn  5957: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5958: 
                   5959: sub fetch_enrollment_query {
1.511     raeburn  5960:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5961:     my $homeserver;
1.547     raeburn  5962:     my $maxtries = 1;
1.508     raeburn  5963:     if ($context eq 'automated') {
                   5964:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5965:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5966:     } else {
                   5967:         $homeserver = &homeserver($cnum,$dom);
                   5968:     }
1.838     albertel 5969:     my $host=&hostname($homeserver);
1.506     raeburn  5970:     my $cmd = '';
1.1000    raeburn  5971:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5972:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5973:     }
                   5974:     $cmd =~ s/%%$//;
                   5975:     $cmd = &escape($cmd);
                   5976:     my $query = 'fetchenrollment';
1.620     albertel 5977:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5978:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5979:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5980:         return 'error: '.$queryid;
                   5981:     }
1.506     raeburn  5982:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5983:     my $tries = 1;
                   5984:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5985:         $reply = &get_query_reply($queryid);
                   5986:         $tries ++;
                   5987:     }
1.526     raeburn  5988:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5989:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5990:     } else {
1.901     albertel 5991:         my @responses = split(/:/,$reply);
1.515     raeburn  5992:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5993:             foreach my $line (@responses) {
                   5994:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5995:                 $$replyref{$key} = $value;
                   5996:             }
                   5997:         } else {
1.506     raeburn  5998:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5999:             foreach my $line (@responses) {
                   6000:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6001:                 $$replyref{$key} = $value;
                   6002:                 if ($value > 0) {
1.800     albertel 6003:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6004:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6005:                         my $destname = $pathname.'/'.$filename;
                   6006:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6007:                         if ($xml_classlist =~ /^error/) {
                   6008:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6009:                         } else {
1.506     raeburn  6010:                             if ( open(FILE,">$destname") ) {
                   6011:                                 print FILE &unescape($xml_classlist);
                   6012:                                 close(FILE);
1.526     raeburn  6013:                             } else {
                   6014:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6015:                             }
                   6016:                         }
                   6017:                     }
                   6018:                 }
                   6019:             }
                   6020:         }
                   6021:         return 'ok';
                   6022:     }
                   6023:     return 'error';
                   6024: }
                   6025: 
1.242     www      6026: sub get_query_reply {
                   6027:     my $queryid=shift;
1.240     www      6028:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6029:     my $reply='';
                   6030:     for (1..100) {
                   6031: 	sleep 2;
                   6032:         if (-e $replyfile.'.end') {
1.448     albertel 6033: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6034: 		$reply = join('',<$fh>);
                   6035: 		close($fh);
1.240     www      6036: 	   } else { return 'error: reply_file_error'; }
1.242     www      6037:            return &unescape($reply);
                   6038: 	}
1.240     www      6039:     }
1.242     www      6040:     return 'timeout:'.$queryid;
1.240     www      6041: }
                   6042: 
                   6043: sub courselog_query {
1.241     www      6044: #
                   6045: # possible filters:
                   6046: # url: url or symb
                   6047: # username
                   6048: # domain
                   6049: # action: view, submit, grade
                   6050: # start: timestamp
                   6051: # end: timestamp
                   6052: #
1.240     www      6053:     my (%filters)=@_;
1.620     albertel 6054:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6055:     if ($filters{'url'}) {
                   6056: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6057:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6058:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6059:     }
1.620     albertel 6060:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6061:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6062:     return &log_query($cname,$cdom,'courselog',%filters);
                   6063: }
                   6064: 
                   6065: sub userlog_query {
1.858     raeburn  6066: #
                   6067: # possible filters:
                   6068: # action: log check role
                   6069: # start: timestamp
                   6070: # end: timestamp
                   6071: #
1.240     www      6072:     my ($uname,$udom,%filters)=@_;
                   6073:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6074: }
                   6075: 
1.506     raeburn  6076: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6077: 
                   6078: sub auto_run {
1.508     raeburn  6079:     my ($cnum,$cdom) = @_;
1.876     raeburn  6080:     my $response = 0;
                   6081:     my $settings;
                   6082:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6083:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6084:         $settings = $domconfig{'autoenroll'};
                   6085:         if ($settings->{'run'} eq '1') {
                   6086:             $response = 1;
                   6087:         }
                   6088:     } else {
1.934     raeburn  6089:         my $homeserver;
                   6090:         if (&is_course($cdom,$cnum)) {
                   6091:             $homeserver = &homeserver($cnum,$cdom);
                   6092:         } else {
                   6093:             $homeserver = &domain($cdom,'primary');
                   6094:         }
                   6095:         if ($homeserver ne 'no_host') {
                   6096:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6097:         }
1.876     raeburn  6098:     }
1.506     raeburn  6099:     return $response;
                   6100: }
1.776     albertel 6101: 
1.506     raeburn  6102: sub auto_get_sections {
1.508     raeburn  6103:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6104:     my $homeserver;
                   6105:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6106:         $homeserver = &homeserver($cnum,$cdom);
                   6107:     }
                   6108:     if (!defined($homeserver)) { 
                   6109:         if ($cdom =~ /^$match_domain$/) {
                   6110:             $homeserver = &domain($cdom,'primary');
                   6111:         }
                   6112:     }
                   6113:     my @secs;
                   6114:     if (defined($homeserver)) {
                   6115:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6116:         unless ($response eq 'refused') {
                   6117:             @secs = split(/:/,$response);
                   6118:         }
1.506     raeburn  6119:     }
                   6120:     return @secs;
                   6121: }
1.776     albertel 6122: 
1.506     raeburn  6123: sub auto_new_course {
1.1099    raeburn  6124:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6125:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6126:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6127:     return $response;
                   6128: }
1.776     albertel 6129: 
1.506     raeburn  6130: sub auto_validate_courseID {
1.508     raeburn  6131:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6132:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6133:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6134:     return $response;
                   6135: }
1.776     albertel 6136: 
1.1007    raeburn  6137: sub auto_validate_instcode {
1.1020    raeburn  6138:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6139:     my ($homeserver,$response);
                   6140:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6141:         $homeserver = &homeserver($cnum,$cdom);
                   6142:     }
                   6143:     if (!defined($homeserver)) {
                   6144:         if ($cdom =~ /^$match_domain$/) {
                   6145:             $homeserver = &domain($cdom,'primary');
                   6146:         }
                   6147:     }
1.1065    raeburn  6148:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6149:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6150:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6151:     return ($outcome,$description);
1.1007    raeburn  6152: }
                   6153: 
1.506     raeburn  6154: sub auto_create_password {
1.873     raeburn  6155:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6156:     my ($homeserver,$response);
1.506     raeburn  6157:     my $create_passwd = 0;
                   6158:     my $authchk = '';
1.873     raeburn  6159:     if ($udom =~ /^$match_domain$/) {
                   6160:         $homeserver = &domain($udom,'primary');
                   6161:     }
                   6162:     if ($homeserver eq '') {
                   6163:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6164:             $homeserver = &homeserver($cnum,$cdom);
                   6165:         }
                   6166:     }
                   6167:     if ($homeserver eq '') {
                   6168:         $authchk = 'nodomain';
1.506     raeburn  6169:     } else {
1.873     raeburn  6170:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6171:         if ($response eq 'refused') {
                   6172:             $authchk = 'refused';
                   6173:         } else {
1.901     albertel 6174:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6175:         }
1.506     raeburn  6176:     }
                   6177:     return ($authparam,$create_passwd,$authchk);
                   6178: }
                   6179: 
1.706     raeburn  6180: sub auto_photo_permission {
                   6181:     my ($cnum,$cdom,$students) = @_;
                   6182:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6183:     my ($outcome,$perm_reqd,$conditions) = 
                   6184: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6185:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6186: 	return (undef,undef);
                   6187:     }
1.706     raeburn  6188:     return ($outcome,$perm_reqd,$conditions);
                   6189: }
                   6190: 
                   6191: sub auto_checkphotos {
                   6192:     my ($uname,$udom,$pid) = @_;
                   6193:     my $homeserver = &homeserver($uname,$udom);
                   6194:     my ($result,$resulttype);
                   6195:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6196: 				   &escape($uname).':'.&escape($pid),
                   6197: 				   $homeserver));
1.709     albertel 6198:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6199: 	return (undef,undef);
                   6200:     }
1.706     raeburn  6201:     if ($outcome) {
                   6202:         ($result,$resulttype) = split(/:/,$outcome);
                   6203:     } 
                   6204:     return ($result,$resulttype);
                   6205: }
                   6206: 
                   6207: sub auto_photochoice {
                   6208:     my ($cnum,$cdom) = @_;
                   6209:     my $homeserver = &homeserver($cnum,$cdom);
                   6210:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6211: 						       &escape($cdom),
                   6212: 						       $homeserver)));
1.709     albertel 6213:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6214: 	return (undef,undef);
                   6215:     }
1.706     raeburn  6216:     return ($update,$comment);
                   6217: }
                   6218: 
                   6219: sub auto_photoupdate {
                   6220:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6221:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6222:     my $host=&hostname($homeserver);
1.706     raeburn  6223:     my $cmd = '';
                   6224:     my $maxtries = 1;
1.800     albertel 6225:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6226:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6227:     }
                   6228:     $cmd =~ s/%%$//;
                   6229:     $cmd = &escape($cmd);
                   6230:     my $query = 'institutionalphotos';
                   6231:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6232:     unless ($queryid=~/^\Q$host\E\_/) {
                   6233:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6234:         return 'error: '.$queryid;
                   6235:     }
                   6236:     my $reply = &get_query_reply($queryid);
                   6237:     my $tries = 1;
                   6238:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6239:         $reply = &get_query_reply($queryid);
                   6240:         $tries ++;
                   6241:     }
                   6242:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6243:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6244:     } else {
                   6245:         my @responses = split(/:/,$reply);
                   6246:         my $outcome = shift(@responses); 
                   6247:         foreach my $item (@responses) {
                   6248:             my ($key,$value) = split(/=/,$item);
                   6249:             $$photo{$key} = $value;
                   6250:         }
                   6251:         return $outcome;
                   6252:     }
                   6253:     return 'error';
                   6254: }
                   6255: 
1.521     raeburn  6256: sub auto_instcode_format {
1.793     albertel 6257:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6258: 	$cat_order) = @_;
1.521     raeburn  6259:     my $courses = '';
1.772     raeburn  6260:     my @homeservers;
1.521     raeburn  6261:     if ($caller eq 'global') {
1.841     albertel 6262: 	my %servers = &get_servers($codedom,'library');
                   6263: 	foreach my $tryserver (keys(%servers)) {
                   6264: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6265: 		push(@homeservers,$tryserver);
                   6266: 	    }
1.584     raeburn  6267:         }
1.1022    raeburn  6268:     } elsif ($caller eq 'requests') {
                   6269:         if ($codedom =~ /^$match_domain$/) {
                   6270:             my $chome = &domain($codedom,'primary');
                   6271:             unless ($chome eq 'no_host') {
                   6272:                 push(@homeservers,$chome);
                   6273:             }
                   6274:         }
1.521     raeburn  6275:     } else {
1.772     raeburn  6276:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6277:     }
1.793     albertel 6278:     foreach my $code (keys(%{$instcodes})) {
                   6279:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6280:     }
                   6281:     chop($courses);
1.772     raeburn  6282:     my $ok_response = 0;
                   6283:     my $response;
                   6284:     while (@homeservers > 0 && $ok_response == 0) {
                   6285:         my $server = shift(@homeservers); 
                   6286:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6287:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6288:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6289: 		split(/:/,$response);
1.772     raeburn  6290:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6291:             push(@{$codetitles},&str2array($codetitles_str));
                   6292:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6293:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6294:             $ok_response = 1;
                   6295:         }
                   6296:     }
                   6297:     if ($ok_response) {
1.521     raeburn  6298:         return 'ok';
1.772     raeburn  6299:     } else {
                   6300:         return $response;
1.521     raeburn  6301:     }
                   6302: }
                   6303: 
1.792     raeburn  6304: sub auto_instcode_defaults {
                   6305:     my ($domain,$returnhash,$code_order) = @_;
                   6306:     my @homeservers;
1.841     albertel 6307: 
                   6308:     my %servers = &get_servers($domain,'library');
                   6309:     foreach my $tryserver (keys(%servers)) {
                   6310: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6311: 	    push(@homeservers,$tryserver);
                   6312: 	}
1.792     raeburn  6313:     }
1.841     albertel 6314: 
1.792     raeburn  6315:     my $response;
1.841     albertel 6316:     foreach my $server (@homeservers) {
1.792     raeburn  6317:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6318:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6319: 	
                   6320: 	foreach my $pair (split(/\&/,$response)) {
                   6321: 	    my ($name,$value)=split(/\=/,$pair);
                   6322: 	    if ($name eq 'code_order') {
                   6323: 		@{$code_order} = split(/\&/,&unescape($value));
                   6324: 	    } else {
                   6325: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6326: 	    }
                   6327: 	}
                   6328: 	return 'ok';
1.792     raeburn  6329:     }
1.841     albertel 6330: 
                   6331:     return $response;
1.1003    raeburn  6332: }
                   6333: 
                   6334: sub auto_possible_instcodes {
1.1007    raeburn  6335:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6336:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6337:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6338:         return;
                   6339:     }
1.1003    raeburn  6340:     my (@homeservers,$uhome);
                   6341:     if (defined(&domain($domain,'primary'))) {
                   6342:         $uhome=&domain($domain,'primary');
                   6343:         push(@homeservers,&domain($domain,'primary'));
                   6344:     } else {
                   6345:         my %servers = &get_servers($domain,'library');
                   6346:         foreach my $tryserver (keys(%servers)) {
                   6347:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6348:                 push(@homeservers,$tryserver);
                   6349:             }
                   6350:         }
                   6351:     }
                   6352:     my $response;
                   6353:     foreach my $server (@homeservers) {
                   6354:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6355:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6356:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6357:             split(':',$response);
                   6358:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6359:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6360:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6361:             my ($name,$value)=split('=',$item);
                   6362:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6363:         }
                   6364:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6365:             my ($name,$value)=split('=',$item);
                   6366:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6367:         }
                   6368:         return 'ok';
                   6369:     }
                   6370:     return $response;
                   6371: }
1.792     raeburn  6372: 
1.1010    raeburn  6373: sub auto_courserequest_checks {
                   6374:     my ($dom) = @_;
1.1020    raeburn  6375:     my ($homeserver,%validations);
                   6376:     if ($dom =~ /^$match_domain$/) {
                   6377:         $homeserver = &domain($dom,'primary');
                   6378:     }
                   6379:     unless ($homeserver eq 'no_host') {
                   6380:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6381:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6382:             my @items = split(/&/,$response);
                   6383:             foreach my $item (@items) {
                   6384:                 my ($key,$value) = split('=',$item);
                   6385:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6386:             }
                   6387:         }
                   6388:     }
1.1010    raeburn  6389:     return %validations; 
                   6390: }
                   6391: 
1.1020    raeburn  6392: sub auto_courserequest_validation {
                   6393:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6394:     my ($homeserver,$response);
                   6395:     if ($dom =~ /^$match_domain$/) {
                   6396:         $homeserver = &domain($dom,'primary');
                   6397:     }
                   6398:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6399:           
1.1020    raeburn  6400:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6401:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6402:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6403:                                     $homeserver));
                   6404:     }
                   6405:     return $response;
                   6406: }
                   6407: 
1.777     albertel 6408: sub auto_validate_class_sec {
1.918     raeburn  6409:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6410:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6411:     my $ownerlist;
                   6412:     if (ref($owners) eq 'ARRAY') {
                   6413:         $ownerlist = join(',',@{$owners});
                   6414:     } else {
                   6415:         $ownerlist = $owners;
                   6416:     }
1.773     raeburn  6417:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6418:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6419:     return $response;
                   6420: }
                   6421: 
1.679     raeburn  6422: # ------------------------------------------------------- Course Group routines
                   6423: 
                   6424: sub get_coursegroups {
1.809     raeburn  6425:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6426:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6427: }
                   6428: 
1.679     raeburn  6429: sub modify_coursegroup {
                   6430:     my ($cdom,$cnum,$groupsettings) = @_;
                   6431:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6432: }
                   6433: 
1.809     raeburn  6434: sub toggle_coursegroup_status {
                   6435:     my ($cdom,$cnum,$group,$action) = @_;
                   6436:     my ($from_namespace,$to_namespace);
                   6437:     if ($action eq 'delete') {
                   6438:         $from_namespace = 'coursegroups';
                   6439:         $to_namespace = 'deleted_groups';
                   6440:     } else {
                   6441:         $from_namespace = 'deleted_groups';
                   6442:         $to_namespace = 'coursegroups';
                   6443:     }
                   6444:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6445:     if (my $tmp = &error(%curr_group)) {
                   6446:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6447:         return ('read error',$tmp);
                   6448:     } else {
                   6449:         my %savedsettings = %curr_group; 
1.809     raeburn  6450:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6451:         my $deloutcome;
                   6452:         if ($result eq 'ok') {
1.809     raeburn  6453:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6454:         } else {
                   6455:             return ('write error',$result);
                   6456:         }
                   6457:         if ($deloutcome eq 'ok') {
                   6458:             return 'ok';
                   6459:         } else {
                   6460:             return ('delete error',$deloutcome);
                   6461:         }
                   6462:     }
                   6463: }
                   6464: 
1.679     raeburn  6465: sub modify_group_roles {
1.957     raeburn  6466:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6467:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6468:     my $role = 'gr/'.&escape($userprivs);
                   6469:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6470:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6471:     if ($result eq 'ok') {
                   6472:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6473:     }
1.679     raeburn  6474:     return $result;
                   6475: }
                   6476: 
                   6477: sub modify_coursegroup_membership {
                   6478:     my ($cdom,$cnum,$membership) = @_;
                   6479:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6480:     return $result;
                   6481: }
                   6482: 
1.682     raeburn  6483: sub get_active_groups {
                   6484:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6485:     my $now = time;
                   6486:     my %groups = ();
                   6487:     foreach my $key (keys(%env)) {
1.811     albertel 6488:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6489:             my ($start,$end) = split(/\./,$env{$key});
                   6490:             if (($end!=0) && ($end<$now)) { next; }
                   6491:             if (($start!=0) && ($start>$now)) { next; }
                   6492:             if ($1 eq $cdom && $2 eq $cnum) {
                   6493:                 $groups{$3} = $env{$key} ;
                   6494:             }
                   6495:         }
                   6496:     }
                   6497:     return %groups;
                   6498: }
                   6499: 
1.683     raeburn  6500: sub get_group_membership {
                   6501:     my ($cdom,$cnum,$group) = @_;
                   6502:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6503: }
                   6504: 
                   6505: sub get_users_groups {
                   6506:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6507:     my @usersgroups;
1.683     raeburn  6508:     my $cachetime=1800;
                   6509: 
                   6510:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6511:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6512:     if (defined($cached)) {
1.734     albertel 6513:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6514:     } else {  
                   6515:         $grouplist = '';
1.816     raeburn  6516:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6517:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6518:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6519:         my $access_end = $env{'course.'.$courseid.
                   6520:                               '.default_enrollment_end_date'};
                   6521:         my $now = time;
                   6522:         foreach my $key (keys(%roleshash)) {
                   6523:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6524:                 my $group = $1;
                   6525:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6526:                     my $start = $2;
                   6527:                     my $end = $1;
                   6528:                     if ($start == -1) { next; } # deleted from group
                   6529:                     if (($start!=0) && ($start>$now)) { next; }
                   6530:                     if (($end!=0) && ($end<$now)) {
                   6531:                         if ($access_end && $access_end < $now) {
                   6532:                             if ($access_end - $end < 86400) {
                   6533:                                 push(@usersgroups,$group);
1.733     raeburn  6534:                             }
                   6535:                         }
1.817     raeburn  6536:                         next;
1.733     raeburn  6537:                     }
1.817     raeburn  6538:                     push(@usersgroups,$group);
1.683     raeburn  6539:                 }
                   6540:             }
                   6541:         }
1.817     raeburn  6542:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6543:         $grouplist = join(':',@usersgroups);
                   6544:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6545:     }
1.733     raeburn  6546:     return @usersgroups;
1.683     raeburn  6547: }
                   6548: 
                   6549: sub devalidate_getgroups_cache {
                   6550:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6551:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6552: 
1.683     raeburn  6553:     my $hashid="$udom:$uname:$courseid";
                   6554:     &devalidate_cache_new('getgroups',$hashid);
                   6555: }
                   6556: 
1.12      www      6557: # ------------------------------------------------------------------ Plain Text
                   6558: 
                   6559: sub plaintext {
1.988     raeburn  6560:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6561:     if ($short =~ m{^cr/}) {
1.758     albertel 6562: 	return (split('/',$short))[-1];
                   6563:     }
1.742     raeburn  6564:     if (!defined($cid)) {
                   6565:         $cid = $env{'request.course.id'};
                   6566:     }
                   6567:     my %rolenames = (
1.1008    raeburn  6568:                       Course    => 'std',
                   6569:                       Community => 'alt1',
1.742     raeburn  6570:                     );
1.1037    raeburn  6571:     if ($cid ne '') {
                   6572:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6573:             unless ($forcedefault) {
                   6574:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6575:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6576:                 return &Apache::lonlocal::mt($roletext);
                   6577:             }
                   6578:         }
                   6579:     }
                   6580:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6581:         (defined($rolenames{$type})) && 
                   6582:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6583:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6584:     } elsif ($cid ne '') {
                   6585:         my $crstype = $env{'course.'.$cid.'.type'};
                   6586:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6587:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6588:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6589:         }
1.742     raeburn  6590:     }
1.1037    raeburn  6591:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6592: }
                   6593: 
                   6594: # ----------------------------------------------------------------- Assign Role
                   6595: 
                   6596: sub assignrole {
1.957     raeburn  6597:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6598:         $context)=@_;
1.21      www      6599:     my $mrole;
                   6600:     if ($role =~ /^cr\//) {
1.393     www      6601:         my $cwosec=$url;
1.811     albertel 6602:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6603: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6604:            my $refused = 1;
                   6605:            if ($context eq 'requestcourses') {
                   6606:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6607:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6608:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6609:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6610:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6611:                            if ($crsenv{'internal.courseowner'} eq
                   6612:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6613:                                $refused = '';
                   6614:                            }
                   6615:                        }
                   6616:                    }
                   6617:                }
                   6618:            }
                   6619:            if ($refused) {
                   6620:                &logthis('Refused custom assignrole: '.
                   6621:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6622:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6623:                return 'refused';
                   6624:            }
1.104     www      6625:         }
1.21      www      6626:         $mrole='cr';
1.678     raeburn  6627:     } elsif ($role =~ /^gr\//) {
                   6628:         my $cwogrp=$url;
1.811     albertel 6629:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6630:         unless (&allowed('mdg',$cwogrp)) {
                   6631:             &logthis('Refused group assignrole: '.
                   6632:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6633:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6634:             return 'refused';
                   6635:         }
                   6636:         $mrole='gr';
1.21      www      6637:     } else {
1.82      www      6638:         my $cwosec=$url;
1.811     albertel 6639:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6640:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6641:             my $refused;
                   6642:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6643:                 if (!(&allowed('c'.$role,$url))) {
                   6644:                     $refused = 1;
                   6645:                 }
                   6646:             } else {
                   6647:                 $refused = 1;
                   6648:             }
1.947     raeburn  6649:             if ($refused) {
1.1045    raeburn  6650:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6651:                 if (!$selfenroll && $context eq 'course') {
                   6652:                     my %crsenv;
                   6653:                     if ($role eq 'cc' || $role eq 'co') {
                   6654:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6655:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6656:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6657:                                 if ($crsenv{'internal.courseowner'} eq 
                   6658:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6659:                                     $refused = '';
                   6660:                                 }
                   6661:                             }
                   6662:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6663:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6664:                                 if ($crsenv{'internal.courseowner'} eq 
                   6665:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6666:                                     $refused = '';
                   6667:                                 }
                   6668:                             }
                   6669:                         }
                   6670:                     }
                   6671:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6672:                     $refused = '';
1.1017    raeburn  6673:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6674:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6675:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6676:                         my $wrongcc;
                   6677:                         if ($cnum =~ /^$match_community$/) {
                   6678:                             $wrongcc = 1 if ($role eq 'cc');
                   6679:                         } else {
                   6680:                             $wrongcc = 1 if ($role eq 'co');
                   6681:                         }
                   6682:                         unless ($wrongcc) {
                   6683:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6684:                             if ($crsenv{'internal.courseowner'} eq 
                   6685:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6686:                                 $refused = '';
                   6687:                             }
1.1017    raeburn  6688:                         }
                   6689:                     }
                   6690:                 }
                   6691:                 if ($refused) {
1.947     raeburn  6692:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6693:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6694: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6695:                     return 'refused';
                   6696:                 }
1.932     raeburn  6697:             }
1.104     www      6698:         }
1.21      www      6699:         $mrole=$role;
                   6700:     }
1.620     albertel 6701:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6702:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6703:     if ($end) { $command.='_'.$end; }
1.21      www      6704:     if ($start) {
                   6705: 	if ($end) { 
1.81      www      6706:            $command.='_'.$start; 
1.21      www      6707:         } else {
1.81      www      6708:            $command.='_0_'.$start;
1.21      www      6709:         }
                   6710:     }
1.739     raeburn  6711:     my $origstart = $start;
                   6712:     my $origend = $end;
1.957     raeburn  6713:     my $delflag;
1.357     www      6714: # actually delete
                   6715:     if ($deleteflag) {
1.373     www      6716: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6717: # modify command to delete the role
1.620     albertel 6718:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6719:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6720: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6721: # set start and finish to negative values for userrolelog
                   6722:            $start=-1;
                   6723:            $end=-1;
1.957     raeburn  6724:            $delflag = 1;
1.357     www      6725:         }
                   6726:     }
                   6727: # send command
1.349     www      6728:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6729: # log new user role if status is ok
1.349     www      6730:     if ($answer eq 'ok') {
1.663     raeburn  6731: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6732: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6733:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6734:         unless ($role =~ /^gr/) {
                   6735:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6736:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6737:         }
1.1053    raeburn  6738:         if ($role eq 'cc') {
                   6739:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6740:         }
1.349     www      6741:     }
                   6742:     return $answer;
1.169     harris41 6743: }
                   6744: 
1.1053    raeburn  6745: sub autoupdate_coowners {
                   6746:     my ($url,$end,$start,$uname,$udom) = @_;
                   6747:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6748:     if (($cdom ne '') && ($cnum ne '')) {
                   6749:         my $now = time;
                   6750:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6751:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6752:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6753:             my $instcode = $coursehash{'internal.coursecode'};
                   6754:             if ($instcode ne '') {
1.1056    raeburn  6755:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6756:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6757:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6758:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6759:                         if ($result eq 'valid') {
                   6760:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6761:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6762:                                     push(@newcoowners,$coowner);
                   6763:                                 }
                   6764:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6765:                                     push(@newcoowners,$uname.':'.$udom);
                   6766:                                 }
                   6767:                                 @newcoowners = sort(@newcoowners);
                   6768:                             } else {
                   6769:                                 push(@newcoowners,$uname.':'.$udom);
                   6770:                             }
                   6771:                         } else {
                   6772:                             if ($coursehash{'internal.co-owners'}) {
                   6773:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6774:                                     unless ($coowner eq $uname.':'.$udom) {
                   6775:                                         push(@newcoowners,$coowner);
                   6776:                                     }
                   6777:                                 }
                   6778:                                 unless (@newcoowners > 0) {
                   6779:                                     $delcoowners = 1;
                   6780:                                     $coowners = '';
                   6781:                                 }
                   6782:                             }
                   6783:                         }
                   6784:                         if (@newcoowners || $delcoowners) {
                   6785:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6786:                                             $delcoowners,@newcoowners);
                   6787:                         }
                   6788:                     }
                   6789:                 }
                   6790:             }
                   6791:         }
                   6792:     }
                   6793: }
                   6794: 
                   6795: sub store_coowners {
                   6796:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6797:     my $cid = $cdom.'_'.$cnum;
                   6798:     my ($coowners,$delresult,$putresult);
                   6799:     if (@newcoowners) {
                   6800:         $coowners = join(',',@newcoowners);
                   6801:         my %coownershash = (
                   6802:                             'internal.co-owners' => $coowners,
                   6803:                            );
                   6804:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6805:         if ($putresult eq 'ok') {
                   6806:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6807:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6808:             }
                   6809:         }
                   6810:     }
                   6811:     if ($delcoowners) {
                   6812:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6813:         if ($delresult eq 'ok') {
                   6814:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6815:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6816:             }
                   6817:         }
                   6818:     }
                   6819:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6820:         my %crsinfo =
                   6821:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6822:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6823:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6824:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6825:         }
                   6826:     }
                   6827: }
                   6828: 
1.169     harris41 6829: # -------------------------------------------------- Modify user authentication
1.197     www      6830: # Overrides without validation
                   6831: 
1.169     harris41 6832: sub modifyuserauth {
                   6833:     my ($udom,$uname,$umode,$upass)=@_;
                   6834:     my $uhome=&homeserver($uname,$udom);
1.197     www      6835:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6836:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6837:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6838:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6839:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6840: 		     &escape($upass),$uhome);
1.620     albertel 6841:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6842:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6843:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6844:     &log($udom,,$uname,$uhome,
1.620     albertel 6845:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6846:                                      $env{'user.name'}.', '.$umode.
1.197     www      6847:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6848:     unless ($reply eq 'ok') {
1.197     www      6849:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6850: 	return 'error: '.$reply;
                   6851:     }   
1.170     harris41 6852:     return 'ok';
1.80      www      6853: }
                   6854: 
1.81      www      6855: # --------------------------------------------------------------- Modify a user
1.80      www      6856: 
1.81      www      6857: sub modifyuser {
1.206     matthew  6858:     my ($udom,    $uname, $uid,
                   6859:         $umode,   $upass, $first,
                   6860:         $middle,  $last,  $gene,
1.1058    raeburn  6861:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6862:     $udom= &LONCAPA::clean_domain($udom);
                   6863:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  6864:     my $showcandelete = 'none';
                   6865:     if (ref($candelete) eq 'ARRAY') {
                   6866:         if (@{$candelete} > 0) {
                   6867:             $showcandelete = join(', ',@{$candelete});
                   6868:         }
                   6869:     }
1.81      www      6870:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6871:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  6872: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6873:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6874:                                      ' desiredhome not specified'). 
1.620     albertel 6875:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6876:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6877:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  6878:     my $newuser;
                   6879:     if ($uhome eq 'no_host') {
                   6880:         $newuser = 1;
                   6881:     }
1.80      www      6882: # ----------------------------------------------------------------- Create User
1.406     albertel 6883:     if (($uhome eq 'no_host') && 
                   6884: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6885:         my $unhome='';
1.844     albertel 6886:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6887:             $unhome = $desiredhome;
1.620     albertel 6888: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6889: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6890:         } else { # load balancing routine for determining $unhome
1.81      www      6891:             my $loadm=10000000;
1.841     albertel 6892: 	    my %servers = &get_servers($udom,'library');
                   6893: 	    foreach my $tryserver (keys(%servers)) {
                   6894: 		my $answer=reply('load',$tryserver);
                   6895: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6896: 		    $loadm=$answer;
                   6897: 		    $unhome=$tryserver;
                   6898: 		}
1.80      www      6899: 	    }
                   6900:         }
                   6901:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6902: 	    return 'error: unable to find a home server for '.$uname.
                   6903:                    ' in domain '.$udom;
1.80      www      6904:         }
                   6905:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6906:                          &escape($upass),$unhome);
                   6907: 	unless ($reply eq 'ok') {
                   6908:             return 'error: '.$reply;
                   6909:         }   
1.230     stredwic 6910:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6911:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6912: 	    return 'error: unable verify users home machine.';
1.80      www      6913:         }
1.209     matthew  6914:     }   # End of creation of new user
1.80      www      6915: # ---------------------------------------------------------------------- Add ID
                   6916:     if ($uid) {
                   6917:        $uid=~tr/A-Z/a-z/;
                   6918:        my %uidhash=&idrget($udom,$uname);
1.196     www      6919:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6920:          && (!$forceid)) {
1.80      www      6921: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6922: 	      return 'error: user id "'.$uid.'" does not match '.
                   6923:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6924:           }
                   6925:        } else {
                   6926: 	  &idput($udom,($uname => $uid));
                   6927:        }
                   6928:     }
                   6929: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6930:     my @tmp=&get('environment',
1.899     raeburn  6931: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6932:                     'permanentemail','inststatus'],
1.134     albertel 6933: 		   $udom,$uname);
1.1075    raeburn  6934:     my (%names,%oldnames);
1.313     matthew  6935:     if ($tmp[0] =~ m/^error:.*/) { 
                   6936:         %names=(); 
                   6937:     } else {
                   6938:         %names = @tmp;
1.1075    raeburn  6939:         %oldnames = %names;
1.313     matthew  6940:     }
1.388     www      6941: #
1.1058    raeburn  6942: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6943: # of users did not contain them), do not overwrite existing values
                   6944: # unless field is in $candelete array ref.  
                   6945: #
                   6946: 
                   6947:     my @fields = ('firstname','middlename','lastname','generation',
                   6948:                   'permanentemail','id');
                   6949:     my %newvalues;
                   6950:     if (ref($candelete) eq 'ARRAY') {
                   6951:         foreach my $field (@fields) {
                   6952:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6953:                 if ($field eq 'firstname') {
                   6954:                     $names{$field} = $first;
                   6955:                 } elsif ($field eq 'middlename') {
                   6956:                     $names{$field} = $middle;
                   6957:                 } elsif ($field eq 'lastname') {
                   6958:                     $names{$field} = $last;
                   6959:                 } elsif ($field eq 'generation') { 
                   6960:                     $names{$field} = $gene;
                   6961:                 } elsif ($field eq 'permanentemail') {
                   6962:                     $names{$field} = $email;
                   6963:                 } elsif ($field eq 'id') {
                   6964:                     $names{$field}  = $uid;
                   6965:                 }
                   6966:             }
                   6967:         }
                   6968:     }
1.388     www      6969:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6970:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6971:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6972:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6973:     if ($email) {
                   6974:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6975:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6976:     }
1.899     raeburn  6977:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6978:     if (defined($inststatus)) {
                   6979:         $names{'inststatus'} = '';
                   6980:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6981:         if (ref($usertypes) eq 'HASH') {
                   6982:             my @okstatuses; 
                   6983:             foreach my $item (split(/:/,$inststatus)) {
                   6984:                 if (defined($usertypes->{$item})) {
                   6985:                     push(@okstatuses,$item);  
                   6986:                 }
                   6987:             }
                   6988:             if (@okstatuses) {
                   6989:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6990:             }
                   6991:         }
                   6992:     }
1.1075    raeburn  6993:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6994:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  6995:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  6996:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6997:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6998:     } else {
                   6999:         $logmsg .= ' during self creation';
                   7000:     }
1.1075    raeburn  7001:     my $changed;
                   7002:     if ($newuser) {
                   7003:         $changed = 1;
                   7004:     } else {
                   7005:         foreach my $field (@fields) {
                   7006:             if ($names{$field} ne $oldnames{$field}) {
                   7007:                 $changed = 1;
                   7008:                 last;
                   7009:             }
                   7010:         }
                   7011:     }
                   7012:     unless ($changed) {
                   7013:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7014:         &logthis($logmsg);
                   7015:         return 'ok';
                   7016:     }
                   7017:     my $reply = &put('environment', \%names, $udom,$uname);
                   7018:     if ($reply ne 'ok') { 
                   7019:         return 'error: '.$reply;
                   7020:     }
1.1087    raeburn  7021:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7022:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7023:     }
1.1075    raeburn  7024:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7025:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7026:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7027:     &logthis($logmsg);
1.134     albertel 7028:     return 'ok';
1.80      www      7029: }
                   7030: 
1.81      www      7031: # -------------------------------------------------------------- Modify student
1.80      www      7032: 
1.81      www      7033: sub modifystudent {
                   7034:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7035:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7036:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7037:     if (!$cid) {
1.620     albertel 7038: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7039: 	    return 'not_in_class';
                   7040: 	}
1.80      www      7041:     }
                   7042: # --------------------------------------------------------------- Make the user
1.81      www      7043:     my $reply=&modifyuser
1.209     matthew  7044: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7045:          $desiredhome,$email,$inststatus);
1.80      www      7046:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7047:     # This will cause &modify_student_enrollment to get the uid from the
                   7048:     # students environment
                   7049:     $uid = undef if (!$forceid);
1.455     albertel 7050:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7051: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7052:     return $reply;
                   7053: }
                   7054: 
                   7055: sub modify_student_enrollment {
1.957     raeburn  7056:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7057:     my ($cdom,$cnum,$chome);
                   7058:     if (!$cid) {
1.620     albertel 7059: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7060: 	    return 'not_in_class';
                   7061: 	}
1.620     albertel 7062: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7063: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7064:     } else {
                   7065: 	($cdom,$cnum)=split(/_/,$cid);
                   7066:     }
1.620     albertel 7067:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7068:     if (!$chome) {
1.457     raeburn  7069: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7070:     }
1.455     albertel 7071:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7072:     # Make sure the user exists
1.81      www      7073:     my $uhome=&homeserver($uname,$udom);
                   7074:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7075: 	return 'error: no such user';
                   7076:     }
1.297     matthew  7077:     # Get student data if we were not given enough information
                   7078:     if (!defined($first)  || $first  eq '' || 
                   7079:         !defined($last)   || $last   eq '' || 
                   7080:         !defined($uid)    || $uid    eq '' || 
                   7081:         !defined($middle) || $middle eq '' || 
                   7082:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7083:         # They did not supply us with enough data to enroll the student, so
                   7084:         # we need to pick up more information.
1.297     matthew  7085:         my %tmp = &get('environment',
1.294     matthew  7086:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7087:                        ,$udom,$uname);
                   7088: 
1.800     albertel 7089:         #foreach my $key (keys(%tmp)) {
                   7090:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7091:         #}
1.294     matthew  7092:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7093:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7094:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7095:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7096:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7097:     }
1.556     albertel 7098:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7099:     my $reply=cput('classlist',
                   7100: 		   {"$uname:$udom" => 
1.515     raeburn  7101: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7102: 		   $cdom,$cnum);
1.81      www      7103:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7104: 	return 'error: '.$reply;
1.652     albertel 7105:     } else {
                   7106: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7107:     }
1.297     matthew  7108:     # Add student role to user
1.83      www      7109:     my $uurl='/'.$cid;
1.81      www      7110:     $uurl=~s/\_/\//g;
                   7111:     if ($usec) {
                   7112: 	$uurl.='/'.$usec;
                   7113:     }
1.957     raeburn  7114:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7115: }
                   7116: 
1.556     albertel 7117: sub format_name {
                   7118:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7119:     my $name;
                   7120:     if ($first ne 'lastname') {
                   7121: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7122:     } else {
                   7123: 	if ($lastname=~/\S/) {
                   7124: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7125: 	    $name=~s/\s+,/,/;
                   7126: 	} else {
                   7127: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7128: 	}
                   7129:     }
                   7130:     $name=~s/^\s+//;
                   7131:     $name=~s/\s+$//;
                   7132:     $name=~s/\s+/ /g;
                   7133:     return $name;
                   7134: }
                   7135: 
1.84      www      7136: # ------------------------------------------------- Write to course preferences
                   7137: 
                   7138: sub writecoursepref {
                   7139:     my ($courseid,%prefs)=@_;
                   7140:     $courseid=~s/^\///;
                   7141:     $courseid=~s/\_/\//g;
                   7142:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7143:     my $chome=homeserver($cnum,$cdomain);
                   7144:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7145: 	return 'error: no such course';
                   7146:     }
                   7147:     my $cstring='';
1.800     albertel 7148:     foreach my $pref (keys(%prefs)) {
                   7149: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7150:     }
1.84      www      7151:     $cstring=~s/\&$//;
                   7152:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7153: }
                   7154: 
                   7155: # ---------------------------------------------------------- Make/modify course
                   7156: 
                   7157: sub createcourse {
1.741     raeburn  7158:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7159:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7160:     $url=&declutter($url);
                   7161:     my $cid='';
1.1028    raeburn  7162:     if ($context eq 'requestcourses') {
                   7163:         my $can_create = 0;
                   7164:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7165:         if ($udom eq $ownerdom) {
                   7166:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7167:                                   $context)) {
                   7168:                 $can_create = 1;
                   7169:             }
                   7170:         } else {
                   7171:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7172:                                            $category);
                   7173:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7174:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7175:                 if (@curr > 0) {
                   7176:                     my @options = qw(approval validate autolimit);
                   7177:                     my $optregex = join('|',@options);
                   7178:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7179:                         $can_create = 1;
                   7180:                     }
                   7181:                 }
                   7182:             }
                   7183:         }
                   7184:         if ($can_create) {
                   7185:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7186:                 unless (&allowed('ccc',$udom)) {
                   7187:                     return 'refused'; 
                   7188:                 }
1.1017    raeburn  7189:             }
                   7190:         } else {
                   7191:             return 'refused';
                   7192:         }
1.1028    raeburn  7193:     } elsif (!&allowed('ccc',$udom)) {
                   7194:         return 'refused';
1.84      www      7195:     }
1.1011    raeburn  7196: # --------------------------------------------------------------- Get Unique ID
                   7197:     my $uname;
                   7198:     if ($cnum =~ /^$match_courseid$/) {
                   7199:         my $chome=&homeserver($cnum,$udom,'true');
                   7200:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7201:             $uname = $cnum;
                   7202:         } else {
1.1038    raeburn  7203:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7204:         }
                   7205:     } else {
1.1038    raeburn  7206:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7207:     }
                   7208:     return $uname if ($uname =~ /^error/);
                   7209: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7210:     if (!defined($course_server)) {
                   7211:         if (defined(&domain($udom,'primary'))) {
                   7212:             $course_server = &domain($udom,'primary');
                   7213:         } else {
                   7214:             $course_server = $env{'user.home'}; 
                   7215:         }
                   7216:     }
                   7217:     my %host_servers =
                   7218:         &Apache::lonnet::get_servers($udom,'library');
                   7219:     unless ($host_servers{$course_server}) {
                   7220:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7221:     }
1.84      www      7222: # ------------------------------------------------------------- Make the course
                   7223:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7224:                       $course_server);
1.84      www      7225:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7226:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7227:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7228: 	return 'error: no such course';
                   7229:     }
1.271     www      7230: # ----------------------------------------------------------------- Course made
1.516     raeburn  7231: # log existence
1.1029    raeburn  7232:     my $now = time;
1.918     raeburn  7233:     my $newcourse = {
                   7234:                     $udom.'_'.$uname => {
1.921     raeburn  7235:                                      description => $description,
                   7236:                                      inst_code   => $inst_code,
                   7237:                                      owner       => $course_owner,
                   7238:                                      type        => $crstype,
1.1029    raeburn  7239:                                      creator     => $env{'user.name'}.':'.
                   7240:                                                     $env{'user.domain'},
                   7241:                                      created     => $now,
                   7242:                                      context     => $context,
1.918     raeburn  7243:                                                 },
                   7244:                     };
1.921     raeburn  7245:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7246: # set toplevel url
1.271     www      7247:     my $topurl=$url;
                   7248:     unless ($nonstandard) {
                   7249: # ------------------------------------------ For standard courses, make top url
                   7250:         my $mapurl=&clutter($url);
1.278     www      7251:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7252:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7253: <map>
                   7254: <resource id="1" type="start"></resource>
                   7255: <resource id="2" src="$mapurl"></resource>
                   7256: <resource id="3" type="finish"></resource>
                   7257: <link index="1" from="1" to="2"></link>
                   7258: <link index="2" from="2" to="3"></link>
                   7259: </map>
                   7260: ENDINITMAP
                   7261:         $topurl=&declutter(
1.638     albertel 7262:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7263:                           );
                   7264:     }
                   7265: # ----------------------------------------------------------- Write preferences
1.84      www      7266:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7267:                      ('description'              => $description,
                   7268:                       'url'                      => $topurl,
                   7269:                       'internal.creator'         => $env{'user.name'}.':'.
                   7270:                                                     $env{'user.domain'},
                   7271:                       'internal.created'         => $now,
                   7272:                       'internal.creationcontext' => $context)
                   7273:                     );
1.84      www      7274:     return '/'.$udom.'/'.$uname;
                   7275: }
                   7276: 
1.1011    raeburn  7277: # ------------------------------------------------------------------- Create ID
                   7278: sub generate_coursenum {
1.1038    raeburn  7279:     my ($udom,$crstype) = @_;
1.1011    raeburn  7280:     my $domdesc = &domain($udom);
                   7281:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7282:     my $first;
                   7283:     if ($crstype eq 'Community') {
                   7284:         $first = '0';
                   7285:     } else {
                   7286:         $first = int(1+rand(9)); 
                   7287:     } 
                   7288:     my $uname=$first.
1.1011    raeburn  7289:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7290:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7291:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7292: # ----------------------------------------------- Make sure that does not exist
                   7293:     my $uhome=&homeserver($uname,$udom,'true');
                   7294:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7295:         if ($crstype eq 'Community') {
                   7296:             $first = '0';
                   7297:         } else {
                   7298:             $first = int(1+rand(9));
                   7299:         }
                   7300:         $uname=$first.
1.1011    raeburn  7301:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7302:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7303:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7304:         $uhome=&homeserver($uname,$udom,'true');
                   7305:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7306:             return 'error: unable to generate unique course-ID';
                   7307:         }
                   7308:     }
                   7309:     return $uname;
                   7310: }
                   7311: 
1.813     albertel 7312: sub is_course {
                   7313:     my ($cdom,$cnum) = @_;
                   7314:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7315: 				undef,'.');
1.813     albertel 7316:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7317:         return 1;
                   7318:     }
                   7319:     return 0;
                   7320: }
                   7321: 
1.1015    raeburn  7322: sub store_userdata {
                   7323:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7324:     my $result;
1.1016    raeburn  7325:     if ($datakey ne '') {
1.1013    raeburn  7326:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7327:             if ($udom eq '' || $uname eq '') {
                   7328:                 $udom = $env{'user.domain'};
                   7329:                 $uname = $env{'user.name'};
                   7330:             }
                   7331:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7332:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7333:                 $result = 'error: no_host';
                   7334:             } else {
                   7335:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7336:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7337: 
                   7338:                 my $namevalue='';
                   7339:                 foreach my $key (keys(%{$storehash})) {
                   7340:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7341:                 }
                   7342:                 $namevalue=~s/\&$//;
1.1105    raeburn  7343:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7344:                                   $namevalue,$uhome);
1.1013    raeburn  7345:             }
                   7346:         } else {
                   7347:             $result = 'error: data to store was not a hash reference'; 
                   7348:         }
                   7349:     } else {
                   7350:         $result= 'error: invalid requestkey'; 
                   7351:     }
                   7352:     return $result;
                   7353: }
                   7354: 
1.21      www      7355: # ---------------------------------------------------------- Assign Custom Role
                   7356: 
                   7357: sub assigncustomrole {
1.957     raeburn  7358:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7359:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7360:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7361: }
                   7362: 
                   7363: # ----------------------------------------------------------------- Revoke Role
                   7364: 
                   7365: sub revokerole {
1.957     raeburn  7366:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7367:     my $now=time;
1.965     raeburn  7368:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7369: }
                   7370: 
                   7371: # ---------------------------------------------------------- Revoke Custom Role
                   7372: 
                   7373: sub revokecustomrole {
1.957     raeburn  7374:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7375:     my $now=time;
1.357     www      7376:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7377:            $deleteflag,$selfenroll,$context);
1.17      www      7378: }
                   7379: 
1.533     banghart 7380: # ------------------------------------------------------------ Disk usage
1.535     albertel 7381: sub diskusage {
1.955     raeburn  7382:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7383:     $directorypath =~ s/\/$//;
                   7384:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7385:                        .&escape($getpropath).':'.&escape($uname).':'
                   7386:                        .&escape($udom),homeserver($uname,$udom));
                   7387:     if ($listing eq 'unknown_cmd') {
                   7388:         if ($getpropath) {
                   7389:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7390:         }
                   7391:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7392:     }
1.514     albertel 7393:     return $listing;
1.512     banghart 7394: }
                   7395: 
1.566     banghart 7396: sub is_locked {
1.1096    raeburn  7397:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7398:     my @check;
                   7399:     my $is_locked;
1.1093    raeburn  7400:     push (@check,$file_name);
1.613     albertel 7401:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7402: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7403:     my ($tmp)=keys(%locked);
                   7404:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7405:     
1.566     banghart 7406:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7407:         $is_locked = 'false';
                   7408:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7409:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7410:                $is_locked = 'true';
1.1096    raeburn  7411:                if (ref($which) eq 'ARRAY') {
                   7412:                    push(@{$which},$entry);
                   7413:                } else {
                   7414:                    last;
                   7415:                }
1.745     raeburn  7416:            }
                   7417:        }
1.566     banghart 7418:     } else {
                   7419:         $is_locked = 'false';
                   7420:     }
1.1093    raeburn  7421:     return $is_locked;
1.566     banghart 7422: }
                   7423: 
1.759     albertel 7424: sub declutter_portfile {
                   7425:     my ($file) = @_;
1.833     albertel 7426:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7427:     return $file;
                   7428: }
                   7429: 
1.559     banghart 7430: # ------------------------------------------------------------- Mark as Read Only
                   7431: 
                   7432: sub mark_as_readonly {
                   7433:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7434:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7435:     my ($tmp)=keys(%current_permissions);
                   7436:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7437:     foreach my $file (@{$files}) {
1.759     albertel 7438: 	$file = &declutter_portfile($file);
1.561     banghart 7439:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7440:     }
1.613     albertel 7441:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7442:     return;
                   7443: }
                   7444: 
1.572     banghart 7445: # ------------------------------------------------------------Save Selected Files
                   7446: 
                   7447: sub save_selected_files {
                   7448:     my ($user, $path, @files) = @_;
                   7449:     my $filename = $user."savedfiles";
1.573     banghart 7450:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7451:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7452:     foreach my $file (@files) {
1.620     albertel 7453:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7454:     }
                   7455:     foreach my $file (@other_files) {
1.574     banghart 7456:         print (OUT $file."\n");
1.572     banghart 7457:     }
1.574     banghart 7458:     close (OUT);
1.572     banghart 7459:     return 'ok';
                   7460: }
                   7461: 
1.574     banghart 7462: sub clear_selected_files {
                   7463:     my ($user) = @_;
                   7464:     my $filename = $user."savedfiles";
                   7465:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7466:     print (OUT undef);
                   7467:     close (OUT);
                   7468:     return ("ok");    
                   7469: }
                   7470: 
1.572     banghart 7471: sub files_in_path {
                   7472:     my ($user, $path) = @_;
                   7473:     my $filename = $user."savedfiles";
                   7474:     my %return_files;
1.574     banghart 7475:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7476:     while (my $line_in = <IN>) {
1.574     banghart 7477:         chomp ($line_in);
                   7478:         my @paths_and_file = split (m!/!, $line_in);
                   7479:         my $file_part = pop (@paths_and_file);
                   7480:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7481:         $path_part.='/';
                   7482:         my $path_and_file = $path_part.$file_part;
                   7483:         if ($path_part eq $path) {
                   7484:             $return_files{$file_part}= 'selected';
                   7485:         }
                   7486:     }
1.574     banghart 7487:     close (IN);
                   7488:     return (\%return_files);
1.572     banghart 7489: }
                   7490: 
                   7491: # called in portfolio select mode, to show files selected NOT in current directory
                   7492: sub files_not_in_path {
                   7493:     my ($user, $path) = @_;
                   7494:     my $filename = $user."savedfiles";
                   7495:     my @return_files;
                   7496:     my $path_part;
1.800     albertel 7497:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7498:     while (my $line = <IN>) {
1.572     banghart 7499:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7500:         my @paths_and_file = split(m|/|, $line);
                   7501:         my $file_part = pop(@paths_and_file);
                   7502:         chomp($file_part);
                   7503:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7504:         $path_part .= '/';
                   7505:         my $path_and_file = $path_part.$file_part;
                   7506:         if ($path_part ne $path) {
1.800     albertel 7507:             push(@return_files, ($path_and_file));
1.572     banghart 7508:         }
                   7509:     }
1.800     albertel 7510:     close(OUT);
1.574     banghart 7511:     return (@return_files);
1.572     banghart 7512: }
                   7513: 
1.745     raeburn  7514: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7515: 
1.745     raeburn  7516: sub get_portfile_permissions {
                   7517:     my ($domain,$user) = @_;
1.613     albertel 7518:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7519:     my ($tmp)=keys(%current_permissions);
                   7520:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7521:     return \%current_permissions;
                   7522: }
                   7523: 
                   7524: #---------------------------------------------Get portfolio file access controls
                   7525: 
1.749     raeburn  7526: sub get_access_controls {
1.745     raeburn  7527:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7528:     my %access;
                   7529:     my $real_file = $file;
                   7530:     $file =~ s/\.meta$//;
1.745     raeburn  7531:     if (defined($file)) {
1.749     raeburn  7532:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7533:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7534:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7535:             }
                   7536:         }
1.745     raeburn  7537:     } else {
1.749     raeburn  7538:         foreach my $key (keys(%{$current_permissions})) {
                   7539:             if ($key =~ /\0accesscontrol$/) {
                   7540:                 if (defined($group)) {
                   7541:                     if ($key !~ m-^\Q$group\E/-) {
                   7542:                         next;
                   7543:                     }
                   7544:                 }
                   7545:                 my ($fullpath) = split(/\0/,$key);
                   7546:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7547:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7548:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7549:                     }
                   7550:                 }
                   7551:             }
                   7552:         }
                   7553:     }
                   7554:     return %access;
                   7555: }
                   7556: 
                   7557: sub modify_access_controls {
                   7558:     my ($file_name,$changes,$domain,$user)=@_;
                   7559:     my ($outcome,$deloutcome);
                   7560:     my %store_permissions;
                   7561:     my %new_values;
                   7562:     my %new_control;
                   7563:     my %translation;
                   7564:     my @deletions = ();
                   7565:     my $now = time;
                   7566:     if (exists($$changes{'activate'})) {
                   7567:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7568:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7569:             my $numnew = scalar(@newitems);
                   7570:             for (my $i=0; $i<$numnew; $i++) {
                   7571:                 my $newkey = $newitems[$i];
                   7572:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7573:                 if ($newkey =~ /^\d+:/) { 
                   7574:                     $newkey =~ s/^(\d+)/$newid/;
                   7575:                     $translation{$1} = $newid;
                   7576:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7577:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7578:                     $translation{$1} = $newid;
                   7579:                 }
1.749     raeburn  7580:                 $new_values{$file_name."\0".$newkey} = 
                   7581:                                           $$changes{'activate'}{$newitems[$i]};
                   7582:                 $new_control{$newkey} = $now;
                   7583:             }
                   7584:         }
                   7585:     }
                   7586:     my %todelete;
                   7587:     my %changed_items;
                   7588:     foreach my $action ('delete','update') {
                   7589:         if (exists($$changes{$action})) {
                   7590:             if (ref($$changes{$action}) eq 'HASH') {
                   7591:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7592:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7593:                     if ($action eq 'delete') { 
                   7594:                         $todelete{$itemnum} = 1;
                   7595:                     } else {
                   7596:                         $changed_items{$itemnum} = $key;
                   7597:                     }
                   7598:                 }
1.745     raeburn  7599:             }
                   7600:         }
1.749     raeburn  7601:     }
                   7602:     # get lock on access controls for file.
                   7603:     my $lockhash = {
                   7604:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7605:                                                        ':'.$env{'user.domain'},
                   7606:                    }; 
                   7607:     my $tries = 0;
                   7608:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7609:    
                   7610:     while (($gotlock ne 'ok') && $tries <3) {
                   7611:         $tries ++;
                   7612:         sleep 1;
                   7613:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7614:     }
                   7615:     if ($gotlock eq 'ok') {
                   7616:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7617:         my ($tmp)=keys(%curr_permissions);
                   7618:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7619:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7620:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7621:             if (ref($curr_controls) eq 'HASH') {
                   7622:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7623:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7624:                     if (defined($todelete{$itemnum})) {
                   7625:                         push(@deletions,$file_name."\0".$control_item);
                   7626:                     } else {
                   7627:                         if (defined($changed_items{$itemnum})) {
                   7628:                             $new_control{$changed_items{$itemnum}} = $now;
                   7629:                             push(@deletions,$file_name."\0".$control_item);
                   7630:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7631:                         } else {
                   7632:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7633:                         }
                   7634:                     }
1.745     raeburn  7635:                 }
                   7636:             }
                   7637:         }
1.970     raeburn  7638:         my ($group);
                   7639:         if (&is_course($domain,$user)) {
                   7640:             ($group,my $file) = split(/\//,$file_name,2);
                   7641:         }
1.749     raeburn  7642:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7643:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7644:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7645:         #  remove lock
                   7646:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7647:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7648:         my $sqlresult =
1.970     raeburn  7649:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7650:                                     $group);
1.749     raeburn  7651:     } else {
                   7652:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7653:     }
1.749     raeburn  7654:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7655: }
                   7656: 
1.827     raeburn  7657: sub make_public_indefinitely {
                   7658:     my ($requrl) = @_;
                   7659:     my $now = time;
                   7660:     my $action = 'activate';
                   7661:     my $aclnum = 0;
                   7662:     if (&is_portfolio_url($requrl)) {
                   7663:         my (undef,$udom,$unum,$file_name,$group) =
                   7664:             &parse_portfolio_url($requrl);
                   7665:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7666:         my %access_controls = &get_access_controls($current_perms,
                   7667:                                                    $group,$file_name);
                   7668:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7669:             my ($num,$scope,$end,$start) = 
                   7670:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7671:             if ($scope eq 'public') {
                   7672:                 if ($start <= $now && $end == 0) {
                   7673:                     $action = 'none';
                   7674:                 } else {
                   7675:                     $action = 'update';
                   7676:                     $aclnum = $num;
                   7677:                 }
                   7678:                 last;
                   7679:             }
                   7680:         }
                   7681:         if ($action eq 'none') {
                   7682:              return 'ok';
                   7683:         } else {
                   7684:             my %changes;
                   7685:             my $newend = 0;
                   7686:             my $newstart = $now;
                   7687:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7688:             $changes{$action}{$newkey} = {
                   7689:                 type => 'public',
                   7690:                 time => {
                   7691:                     start => $newstart,
                   7692:                     end   => $newend,
                   7693:                 },
                   7694:             };
                   7695:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7696:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7697:             return $outcome;
                   7698:         }
                   7699:     } else {
                   7700:         return 'invalid';
                   7701:     }
                   7702: }
                   7703: 
1.745     raeburn  7704: #------------------------------------------------------Get Marked as Read Only
                   7705: 
                   7706: sub get_marked_as_readonly {
                   7707:     my ($domain,$user,$what,$group) = @_;
                   7708:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7709:     my @readonly_files;
1.629     banghart 7710:     my $cmp1=$what;
                   7711:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7712:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7713:         if (defined($group)) {
                   7714:             if ($file_name !~ m-^\Q$group\E/-) {
                   7715:                 next;
                   7716:             }
                   7717:         }
1.561     banghart 7718:         if (ref($value) eq "ARRAY"){
                   7719:             foreach my $stored_what (@{$value}) {
1.629     banghart 7720:                 my $cmp2=$stored_what;
1.759     albertel 7721:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7722:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7723:                 }
1.629     banghart 7724:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7725:                     push(@readonly_files, $file_name);
1.745     raeburn  7726:                     last;
1.563     banghart 7727:                 } elsif (!defined($what)) {
                   7728:                     push(@readonly_files, $file_name);
1.745     raeburn  7729:                     last;
1.561     banghart 7730:                 }
                   7731:             }
1.745     raeburn  7732:         }
1.561     banghart 7733:     }
                   7734:     return @readonly_files;
                   7735: }
1.577     banghart 7736: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7737: 
1.577     banghart 7738: sub get_marked_as_readonly_hash {
1.745     raeburn  7739:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7740:     my %readonly_files;
1.745     raeburn  7741:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7742:         if (defined($group)) {
                   7743:             if ($file_name !~ m-^\Q$group\E/-) {
                   7744:                 next;
                   7745:             }
                   7746:         }
1.577     banghart 7747:         if (ref($value) eq "ARRAY"){
                   7748:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7749:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7750:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7751:                         if ($lock_descriptor eq 'graded') {
                   7752:                             $readonly_files{$file_name} = 'graded';
                   7753:                         } elsif ($lock_descriptor eq 'handback') {
                   7754:                             $readonly_files{$file_name} = 'handback';
                   7755:                         } else {
                   7756:                             if (!exists($readonly_files{$file_name})) {
                   7757:                                 $readonly_files{$file_name} = 'locked';
                   7758:                             }
                   7759:                         }
1.745     raeburn  7760:                     }
1.750     banghart 7761:                 } 
1.577     banghart 7762:             }
                   7763:         } 
                   7764:     }
                   7765:     return %readonly_files;
                   7766: }
1.559     banghart 7767: # ------------------------------------------------------------ Unmark as Read Only
                   7768: 
                   7769: sub unmark_as_readonly {
1.629     banghart 7770:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7771:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7772:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7773:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7774:     my $symb_crs = $what;
                   7775:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7776:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7777:     my ($tmp)=keys(%current_permissions);
                   7778:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7779:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7780:     foreach my $file (@readonly_files) {
1.759     albertel 7781: 	my $clean_file = &declutter_portfile($file);
                   7782: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7783: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7784:         my @new_locks;
                   7785:         my @del_keys;
                   7786:         if (ref($current_locks) eq "ARRAY"){
                   7787:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7788:                 my $compare=$locker;
1.749     raeburn  7789:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7790:                     $compare=join('',@{$locker});
1.746     raeburn  7791:                     if ($compare ne $symb_crs) {
                   7792:                         push(@new_locks, $locker);
                   7793:                     }
1.563     banghart 7794:                 }
                   7795:             }
1.650     albertel 7796:             if (scalar(@new_locks) > 0) {
1.563     banghart 7797:                 $current_permissions{$file} = \@new_locks;
                   7798:             } else {
                   7799:                 push(@del_keys, $file);
1.613     albertel 7800:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7801:                 delete($current_permissions{$file});
1.563     banghart 7802:             }
                   7803:         }
1.561     banghart 7804:     }
1.613     albertel 7805:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7806:     return;
                   7807: }
1.512     banghart 7808: 
1.17      www      7809: # ------------------------------------------------------------ Directory lister
                   7810: 
                   7811: sub dirlist {
1.955     raeburn  7812:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7813:     $uri=~s/^\///;
                   7814:     $uri=~s/\/$//;
1.253     stredwic 7815:     my ($udom, $uname);
1.955     raeburn  7816:     if ($getuserdir) {
1.253     stredwic 7817:         $udom = $userdomain;
                   7818:         $uname = $username;
1.955     raeburn  7819:     } else {
                   7820:         (undef,$udom,$uname)=split(/\//,$uri);
                   7821:         if(defined($userdomain)) {
                   7822:             $udom = $userdomain;
                   7823:         }
                   7824:         if(defined($username)) {
                   7825:             $uname = $username;
                   7826:         }
1.253     stredwic 7827:     }
1.955     raeburn  7828:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7829: 
1.955     raeburn  7830:     $dirRoot = $perlvar{'lonDocRoot'};
                   7831:     if (defined($getpropath)) {
                   7832:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7833:         $dirRoot =~ s/\/$//;
1.955     raeburn  7834:     } elsif (defined($getuserdir)) {
                   7835:         my $subdir=$uname.'__';
                   7836:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7837:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7838:                    ."/$udom/$subdir/$uname";
                   7839:     } elsif (defined($alternateRoot)) {
                   7840:         $dirRoot = $alternateRoot;
1.751     banghart 7841:     }
1.253     stredwic 7842: 
                   7843:     if($udom) {
                   7844:         if($uname) {
1.955     raeburn  7845:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7846:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7847:                               .':'.&escape($uname).':'.&escape($udom),
                   7848:                               &homeserver($uname,$udom));
                   7849:             if ($listing eq 'unknown_cmd') {
                   7850:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7851:                                   &homeserver($uname,$udom));
                   7852:             } else {
                   7853:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7854:             }
1.605     matthew  7855:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7856:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7857: 				  &homeserver($uname,$udom));
1.605     matthew  7858:                 @listing_results = split(/:/,$listing);
                   7859:             } else {
                   7860:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7861:             }
                   7862:             return @listing_results;
1.955     raeburn  7863:         } elsif(!$alternateRoot) {
1.800     albertel 7864:             my %allusers;
1.841     albertel 7865: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7866:  	    foreach my $tryserver (keys(%servers)) {
                   7867:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7868:                                   &escape($udom),$tryserver);
                   7869:                 if ($listing eq 'unknown_cmd') {
                   7870: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7871: 				      $udom, $tryserver);
                   7872:                 } else {
                   7873:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7874:                 }
1.841     albertel 7875: 		if ($listing eq 'unknown_cmd') {
                   7876: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7877: 				      $udom, $tryserver);
                   7878: 		    @listing_results = split(/:/,$listing);
                   7879: 		} else {
                   7880: 		    @listing_results =
                   7881: 			map { &unescape($_); } split(/:/,$listing);
                   7882: 		}
                   7883: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7884: 		    $listing_results[0] ne 'empty'       &&
                   7885: 		    $listing_results[0] ne 'con_lost') {
                   7886: 		    foreach my $line (@listing_results) {
                   7887: 			my ($entry) = split(/&/,$line,2);
                   7888: 			$allusers{$entry} = 1;
                   7889: 		    }
                   7890: 		}
1.253     stredwic 7891:             }
                   7892:             my $alluserstr='';
1.800     albertel 7893:             foreach my $user (sort(keys(%allusers))) {
                   7894:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7895:             }
                   7896:             $alluserstr=~s/:$//;
                   7897:             return split(/:/,$alluserstr);
                   7898:         } else {
1.800     albertel 7899:             return ('missing user name');
1.253     stredwic 7900:         }
1.955     raeburn  7901:     } elsif(!defined($getpropath)) {
1.841     albertel 7902:         my @all_domains = sort(&all_domains());
1.955     raeburn  7903:         foreach my $domain (@all_domains) {
                   7904:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7905:         }
                   7906:         return @all_domains;
                   7907:     } else {
1.800     albertel 7908:         return ('missing domain');
1.275     stredwic 7909:     }
                   7910: }
                   7911: 
                   7912: # --------------------------------------------- GetFileTimestamp
                   7913: # This function utilizes dirlist and returns the date stamp for
                   7914: # when it was last modified.  It will also return an error of -1
                   7915: # if an error occurs
                   7916: 
                   7917: sub GetFileTimestamp {
1.955     raeburn  7918:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7919:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7920:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7921:     my ($fileStat) = 
                   7922:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7923:                                  undef,$getuserdir);
1.275     stredwic 7924:     my @stats = split('&', $fileStat);
                   7925:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7926:         # @stats contains first the filename, then the stat output
                   7927:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7928:     } else {
                   7929:         return -1;
1.253     stredwic 7930:     }
1.26      www      7931: }
                   7932: 
1.712     albertel 7933: sub stat_file {
                   7934:     my ($uri) = @_;
1.787     albertel 7935:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7936: 
1.955     raeburn  7937:     my ($udom,$uname,$file);
1.712     albertel 7938:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7939: 	($udom,$uname,$file) =
1.811     albertel 7940: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7941: 	$file = 'userfiles/'.$file;
                   7942:     }
                   7943:     if ($uri =~ m-^/res/-) {
                   7944: 	($udom,$uname) = 
1.807     albertel 7945: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7946: 	$file = $uri;
                   7947:     }
                   7948: 
                   7949:     if (!$udom || !$uname || !$file) {
                   7950: 	# unable to handle the uri
                   7951: 	return ();
                   7952:     }
1.956     raeburn  7953:     my $getpropath;
                   7954:     if ($file =~ /^userfiles\//) {
                   7955:         $getpropath = 1;
                   7956:     }
1.955     raeburn  7957:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7958:     my @stats = split('&', $result);
1.721     banghart 7959:     
1.712     albertel 7960:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7961: 	shift(@stats); #filename is first
                   7962: 	return @stats;
                   7963:     }
                   7964:     return ();
                   7965: }
                   7966: 
1.26      www      7967: # -------------------------------------------------------- Value of a Condition
                   7968: 
1.713     albertel 7969: # gets the value of a specific preevaluated condition
                   7970: #    stored in the string  $env{user.state.<cid>}
                   7971: # or looks up a condition reference in the bighash and if if hasn't
                   7972: # already been evaluated recurses into docondval to get the value of
                   7973: # the condition, then memoizing it to 
                   7974: #   $env{user.state.<cid>.<condition>}
1.40      www      7975: sub directcondval {
                   7976:     my $number=shift;
1.620     albertel 7977:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7978: 	&Apache::lonuserstate::evalstate();
                   7979:     }
1.713     albertel 7980:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7981: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7982:     } elsif ($number =~ /^_/) {
                   7983: 	my $sub_condition;
                   7984: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7985: 		&GDBM_READER(),0640)) {
                   7986: 	    $sub_condition=$bighash{'conditions'.$number};
                   7987: 	    untie(%bighash);
                   7988: 	}
                   7989: 	my $value = &docondval($sub_condition);
1.949     raeburn  7990: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7991: 	return $value;
                   7992:     }
1.620     albertel 7993:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7994:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7995:     } else {
                   7996:        return 2;
                   7997:     }
                   7998: }
                   7999: 
1.713     albertel 8000: # get the collection of conditions for this resource
1.26      www      8001: sub condval {
                   8002:     my $condidx=shift;
1.54      www      8003:     my $allpathcond='';
1.713     albertel 8004:     foreach my $cond (split(/\|/,$condidx)) {
                   8005: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8006: 	    $allpathcond.=
                   8007: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8008: 	}
1.191     harris41 8009:     }
1.54      www      8010:     $allpathcond=~s/\|$//;
1.713     albertel 8011:     return &docondval($allpathcond);
                   8012: }
                   8013: 
                   8014: #evaluates an expression of conditions
                   8015: sub docondval {
                   8016:     my ($allpathcond) = @_;
                   8017:     my $result=0;
                   8018:     if ($env{'request.course.id'}
                   8019: 	&& defined($allpathcond)) {
                   8020: 	my $operand='|';
                   8021: 	my @stack;
                   8022: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8023: 	    if ($chunk eq '(') {
                   8024: 		push @stack,($operand,$result);
                   8025: 	    } elsif ($chunk eq ')') {
                   8026: 		my $before=pop @stack;
                   8027: 		if (pop @stack eq '&') {
                   8028: 		    $result=$result>$before?$before:$result;
                   8029: 		} else {
                   8030: 		    $result=$result>$before?$result:$before;
                   8031: 		}
                   8032: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8033: 		$operand=$chunk;
                   8034: 	    } else {
                   8035: 		my $new=directcondval($chunk);
                   8036: 		if ($operand eq '&') {
                   8037: 		    $result=$result>$new?$new:$result;
                   8038: 		} else {
                   8039: 		    $result=$result>$new?$result:$new;
                   8040: 		}
                   8041: 	    }
                   8042: 	}
1.26      www      8043:     }
                   8044:     return $result;
1.421     albertel 8045: }
                   8046: 
                   8047: # ---------------------------------------------------- Devalidate courseresdata
                   8048: 
                   8049: sub devalidatecourseresdata {
                   8050:     my ($coursenum,$coursedomain)=@_;
                   8051:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8052:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8053: }
                   8054: 
1.763     www      8055: 
1.200     www      8056: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8057: #
                   8058: #  Parameters:
                   8059: #      $coursenum    - Number of the course.
                   8060: #      $coursedomain - Domain at which the course was created.
                   8061: #  Returns:
                   8062: #     A hash of the course parameters along (I think) with timestamps
                   8063: #     and version info.
1.877     foxr     8064: 
1.624     albertel 8065: sub get_courseresdata {
                   8066:     my ($coursenum,$coursedomain)=@_;
1.200     www      8067:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8068:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8069:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8070:     my %dumpreply;
1.417     albertel 8071:     unless (defined($cached)) {
1.624     albertel 8072: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8073: 	$result=\%dumpreply;
1.251     albertel 8074: 	my ($tmp) = keys(%dumpreply);
                   8075: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8076: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8077: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8078: 	    return $tmp;
1.416     albertel 8079: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8080: 	    $result=undef;
1.599     albertel 8081: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8082: 	}
                   8083:     }
1.624     albertel 8084:     return $result;
                   8085: }
                   8086: 
1.633     albertel 8087: sub devalidateuserresdata {
                   8088:     my ($uname,$udom)=@_;
                   8089:     my $hashid="$udom:$uname";
                   8090:     &devalidate_cache_new('userres',$hashid);
                   8091: }
                   8092: 
1.624     albertel 8093: sub get_userresdata {
                   8094:     my ($uname,$udom)=@_;
                   8095:     #most student don\'t have any data set, check if there is some data
                   8096:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8097: 
                   8098:     my $hashid="$udom:$uname";
                   8099:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8100:     if (!defined($cached)) {
                   8101: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8102: 	$result=\%resourcedata;
                   8103: 	&do_cache_new('userres',$hashid,$result,600);
                   8104:     }
                   8105:     my ($tmp)=keys(%$result);
                   8106:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8107: 	return $result;
                   8108:     }
                   8109:     #error 2 occurs when the .db doesn't exist
                   8110:     if ($tmp!~/error: 2 /) {
1.672     albertel 8111: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8112: 		 " Trying to get resource data for ".
                   8113: 		 $uname." at ".$udom.": ".
                   8114: 		 $tmp."</font>");
                   8115:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8116: 	#&EXT_cache_set($udom,$uname);
                   8117: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8118: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8119:     }
                   8120:     return $tmp;
                   8121: }
1.879     foxr     8122: #----------------------------------------------- resdata - return resource data
                   8123: #  Purpose:
                   8124: #    Return resource data for either users or for a course.
                   8125: #  Parameters:
                   8126: #     $name      - Course/user name.
                   8127: #     $domain    - Name of the domain the user/course is registered on.
                   8128: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8129: #     @which     - Array of names of resources desired.
                   8130: #  Returns:
                   8131: #     The value of the first reasource in @which that is found in the
                   8132: #     resource hash.
                   8133: #  Exceptional Conditions:
                   8134: #     If the $type passed in is not valid (not the string 'course' or 
                   8135: #     'user', an undefined  reference is returned.
                   8136: #     If none of the resources are found, an undef is returned
1.624     albertel 8137: sub resdata {
                   8138:     my ($name,$domain,$type,@which)=@_;
                   8139:     my $result;
                   8140:     if ($type eq 'course') {
                   8141: 	$result=&get_courseresdata($name,$domain);
                   8142:     } elsif ($type eq 'user') {
                   8143: 	$result=&get_userresdata($name,$domain);
                   8144:     }
                   8145:     if (!ref($result)) { return $result; }    
1.251     albertel 8146:     foreach my $item (@which) {
1.927     albertel 8147: 	if (defined($result->{$item->[0]})) {
                   8148: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8149: 	}
1.250     albertel 8150:     }
1.291     albertel 8151:     return undef;
1.200     www      8152: }
                   8153: 
1.379     matthew  8154: #
                   8155: # EXT resource caching routines
                   8156: #
                   8157: 
                   8158: sub clear_EXT_cache_status {
1.383     albertel 8159:     &delenv('cache.EXT.');
1.379     matthew  8160: }
                   8161: 
                   8162: sub EXT_cache_status {
                   8163:     my ($target_domain,$target_user) = @_;
1.383     albertel 8164:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8165:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8166:         # We know already the user has no data
                   8167:         return 1;
                   8168:     } else {
                   8169:         return 0;
                   8170:     }
                   8171: }
                   8172: 
                   8173: sub EXT_cache_set {
                   8174:     my ($target_domain,$target_user) = @_;
1.383     albertel 8175:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8176:     #&appenv({$cachename => time});
1.379     matthew  8177: }
                   8178: 
1.28      www      8179: # --------------------------------------------------------- Value of a Variable
1.58      www      8180: sub EXT {
1.715     albertel 8181: 
1.395     albertel 8182:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8183:     unless ($varname) { return ''; }
1.218     albertel 8184:     #get real user name/domain, courseid and symb
                   8185:     my $courseid;
1.359     albertel 8186:     my $publicuser;
1.427     www      8187:     if ($symbparm) {
                   8188: 	$symbparm=&get_symb_from_alias($symbparm);
                   8189:     }
1.218     albertel 8190:     if (!($uname && $udom)) {
1.790     albertel 8191:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8192:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8193:     } else {
1.620     albertel 8194: 	$courseid=$env{'request.course.id'};
1.218     albertel 8195:     }
1.48      www      8196:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8197:     my $rest;
1.320     albertel 8198:     if (defined($therest[0])) {
1.48      www      8199:        $rest=join('.',@therest);
                   8200:     } else {
                   8201:        $rest='';
                   8202:     }
1.320     albertel 8203: 
1.57      www      8204:     my $qualifierrest=$qualifier;
                   8205:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8206:     my $spacequalifierrest=$space;
                   8207:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8208:     if ($realm eq 'user') {
1.48      www      8209: # --------------------------------------------------------------- user.resource
                   8210: 	if ($space eq 'resource') {
1.651     albertel 8211: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8212: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8213: 		 &&
1.744     albertel 8214: 		 ($symbparm eq &symbread()) ) {	
                   8215: 		# if we are in the middle of processing the resource the
                   8216: 		# get the value we are planning on committing
                   8217:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8218:                     return $Apache::lonhomework::results{$qualifierrest};
                   8219:                 } else {
                   8220:                     return $Apache::lonhomework::history{$qualifierrest};
                   8221:                 }
1.335     albertel 8222: 	    } else {
1.359     albertel 8223: 		my %restored;
1.620     albertel 8224: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8225: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8226: 		} else {
                   8227: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8228: 		}
1.335     albertel 8229: 		return $restored{$qualifierrest};
                   8230: 	    }
1.48      www      8231: # ----------------------------------------------------------------- user.access
                   8232:         } elsif ($space eq 'access') {
1.218     albertel 8233: 	    # FIXME - not supporting calls for a specific user
1.48      www      8234:             return &allowed($qualifier,$rest);
                   8235: # ------------------------------------------ user.preferences, user.environment
                   8236:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8237: 	    if (($uname eq $env{'user.name'}) &&
                   8238: 		($udom eq $env{'user.domain'})) {
                   8239: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8240: 	    } else {
1.359     albertel 8241: 		my %returnhash;
                   8242: 		if (!$publicuser) {
                   8243: 		    %returnhash=&userenvironment($udom,$uname,
                   8244: 						 $qualifierrest);
                   8245: 		}
1.218     albertel 8246: 		return $returnhash{$qualifierrest};
                   8247: 	    }
1.48      www      8248: # ----------------------------------------------------------------- user.course
                   8249:         } elsif ($space eq 'course') {
1.218     albertel 8250: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8251:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8252: # ------------------------------------------------------------------- user.role
                   8253:         } elsif ($space eq 'role') {
1.218     albertel 8254: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8255:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8256:             if ($qualifier eq 'value') {
                   8257: 		return $role;
                   8258:             } elsif ($qualifier eq 'extent') {
                   8259:                 return $where;
                   8260:             }
                   8261: # ----------------------------------------------------------------- user.domain
                   8262:         } elsif ($space eq 'domain') {
1.218     albertel 8263:             return $udom;
1.48      www      8264: # ------------------------------------------------------------------- user.name
                   8265:         } elsif ($space eq 'name') {
1.218     albertel 8266:             return $uname;
1.48      www      8267: # ---------------------------------------------------- Any other user namespace
1.29      www      8268:         } else {
1.359     albertel 8269: 	    my %reply;
                   8270: 	    if (!$publicuser) {
                   8271: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8272: 	    }
                   8273: 	    return $reply{$qualifierrest};
1.48      www      8274:         }
1.236     www      8275:     } elsif ($realm eq 'query') {
                   8276: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8277:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8278: 						[$spacequalifierrest]);
1.620     albertel 8279: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8280:    } elsif ($realm eq 'request') {
1.48      www      8281: # ------------------------------------------------------------- request.browser
                   8282:         if ($space eq 'browser') {
1.430     www      8283: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8284: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8285: 		    return 1;
                   8286: 		} else {
                   8287: 		    return 0;
                   8288: 		}
                   8289: 	    } else {
1.620     albertel 8290: 		return $env{'browser.'.$qualifier};
1.430     www      8291: 	    }
1.57      www      8292: # ------------------------------------------------------------ request.filename
                   8293:         } else {
1.620     albertel 8294:             return $env{'request.'.$spacequalifierrest};
1.29      www      8295:         }
1.28      www      8296:     } elsif ($realm eq 'course') {
1.48      www      8297: # ---------------------------------------------------------- course.description
1.620     albertel 8298:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8299:     } elsif ($realm eq 'resource') {
1.165     www      8300: 
1.620     albertel 8301: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8302: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8303: 	}
1.693     albertel 8304: 
                   8305: 	if ($space eq 'title') {
                   8306: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8307: 	    return &gettitle($symbparm);
                   8308: 	}
                   8309: 	
                   8310: 	if ($space eq 'map') {
                   8311: 	    my ($map) = &decode_symb($symbparm);
                   8312: 	    return &symbread($map);
                   8313: 	}
1.905     albertel 8314: 	if ($space eq 'filename') {
                   8315: 	    if ($symbparm) {
                   8316: 		return &clutter((&decode_symb($symbparm))[2]);
                   8317: 	    }
                   8318: 	    return &hreflocation('',$env{'request.filename'});
                   8319: 	}
1.693     albertel 8320: 
                   8321: 	my ($section, $group, @groups);
1.593     albertel 8322: 	my ($courselevelm,$courselevel);
1.539     albertel 8323: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8324: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8325: 
1.218     albertel 8326: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8327: 
1.60      www      8328: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8329: 	    my $symbp=$symbparm;
1.735     albertel 8330: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8331: 
                   8332: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8333: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8334: 
1.620     albertel 8335: 	    if (($env{'user.name'} eq $uname) &&
                   8336: 		($env{'user.domain'} eq $udom)) {
                   8337: 		$section=$env{'request.course.sec'};
1.733     raeburn  8338:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8339:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8340: 	    } else {
1.539     albertel 8341: 		if (! defined($usection)) {
1.551     albertel 8342: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8343: 		} else {
                   8344: 		    $section = $usection;
                   8345: 		}
1.733     raeburn  8346:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8347: 	    }
                   8348: 
                   8349: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8350: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8351: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8352: 
1.593     albertel 8353: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8354: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8355: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8356: 
1.60      www      8357: # ----------------------------------------------------------- first, check user
1.624     albertel 8358: 
                   8359: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8360: 				       ([$courselevelr,'resource'],
                   8361: 					[$courselevelm,'map'     ],
                   8362: 					[$courselevel, 'course'  ]));
1.931     albertel 8363: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8364: 
1.594     albertel 8365: # ------------------------------------------------ second, check some of course
1.684     raeburn  8366:             my $coursereply;
1.691     raeburn  8367:             if (@groups > 0) {
                   8368:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8369:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8370:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8371:             }
1.96      www      8372: 
1.684     raeburn  8373: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8374: 				  $env{'course.'.$courseid.'.domain'},
                   8375: 				  'course',
                   8376: 				  ([$seclevelr,   'resource'],
                   8377: 				   [$seclevelm,   'map'     ],
                   8378: 				   [$seclevel,    'course'  ],
                   8379: 				   [$courselevelr,'resource']));
                   8380: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8381: 
1.60      www      8382: # ------------------------------------------------------ third, check map parms
1.218     albertel 8383: 	    my %parmhash=();
                   8384: 	    my $thisparm='';
                   8385: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8386: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8387: 		    &GDBM_READER(),0640)) {
1.218     albertel 8388: 		$thisparm=$parmhash{$symbparm};
                   8389: 		untie(%parmhash);
                   8390: 	    }
1.927     albertel 8391: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8392: 	}
1.594     albertel 8393: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8394: 
1.218     albertel 8395: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8396: 	my $filename;
                   8397: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8398: 	if ($symbparm) {
1.409     www      8399: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8400: 	} else {
1.620     albertel 8401: 	    $filename=$env{'request.filename'};
1.282     albertel 8402: 	}
                   8403: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8404: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8405: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8406: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8407: 
1.927     albertel 8408: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8409: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8410: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8411: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8412: 				     $env{'course.'.$courseid.'.domain'},
                   8413: 				     'course',
1.927     albertel 8414: 				     ([$courselevelm,'map'   ],
                   8415: 				      [$courselevel, 'course']));
                   8416: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8417: 	}
1.145     www      8418: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8419: 	unless ($space eq '0') {
1.336     albertel 8420: 	    my @parts=split(/_/,$space);
                   8421: 	    my $id=pop(@parts);
                   8422: 	    my $part=join('_',@parts);
                   8423: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8424: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8425: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8426: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8427: 	}
1.395     albertel 8428: 	if ($recurse) { return undef; }
                   8429: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8430: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8431: # ---------------------------------------------------- Any other user namespace
                   8432:     } elsif ($realm eq 'environment') {
                   8433: # ----------------------------------------------------------------- environment
1.620     albertel 8434: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8435: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8436: 	} else {
1.770     albertel 8437: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8438: 		return '';
                   8439: 	    }
1.219     albertel 8440: 	    my %returnhash=&userenvironment($udom,$uname,
                   8441: 					    $spacequalifierrest);
                   8442: 	    return $returnhash{$spacequalifierrest};
                   8443: 	}
1.28      www      8444:     } elsif ($realm eq 'system') {
1.48      www      8445: # ----------------------------------------------------------------- system.time
                   8446: 	if ($space eq 'time') {
                   8447: 	    return time;
                   8448:         }
1.696     albertel 8449:     } elsif ($realm eq 'server') {
                   8450: # ----------------------------------------------------------------- system.time
                   8451: 	if ($space eq 'name') {
                   8452: 	    return $ENV{'SERVER_NAME'};
                   8453:         }
1.28      www      8454:     }
1.48      www      8455:     return '';
1.61      www      8456: }
                   8457: 
1.927     albertel 8458: sub get_reply {
                   8459:     my ($reply_value) = @_;
1.940     raeburn  8460:     if (ref($reply_value) eq 'ARRAY') {
                   8461:         if (wantarray) {
                   8462: 	    return @$reply_value;
                   8463:         }
                   8464:         return $reply_value->[0];
                   8465:     } else {
                   8466:         return $reply_value;
1.927     albertel 8467:     }
                   8468: }
                   8469: 
1.691     raeburn  8470: sub check_group_parms {
                   8471:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8472:     my @groupitems = ();
                   8473:     my $resultitem;
1.927     albertel 8474:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8475:     foreach my $group (@{$groups}) {
                   8476:         foreach my $level (@levels) {
1.927     albertel 8477:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8478:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8479:         }
                   8480:     }
                   8481:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8482:                             $env{'course.'.$courseid.'.domain'},
                   8483:                                      'course',@groupitems);
                   8484:     return $coursereply;
                   8485: }
                   8486: 
                   8487: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8488:     my ($courseid,@groups) = @_;
                   8489:     @groups = sort(@groups);
1.691     raeburn  8490:     return @groups;
                   8491: }
                   8492: 
1.395     albertel 8493: sub packages_tab_default {
                   8494:     my ($uri,$varname)=@_;
                   8495:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8496: 
                   8497:     my (@extension,@specifics,$do_default);
                   8498:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8499: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8500: 	if ($pack_type eq 'default') {
                   8501: 	    $do_default=1;
                   8502: 	} elsif ($pack_type eq 'extension') {
                   8503: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8504: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8505: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8506: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8507: 	}
                   8508:     }
                   8509:     # first look for a package that matches the requested part id
                   8510:     foreach my $package (@specifics) {
                   8511: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8512: 	next if ($pack_part ne $part);
                   8513: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8514: 	    return $packagetab{"$pack_type&$name&default"};
                   8515: 	}
                   8516:     }
                   8517:     # look for any possible matching non extension_ package
                   8518:     foreach my $package (@specifics) {
                   8519: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8520: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8521: 	    return $packagetab{"$pack_type&$name&default"};
                   8522: 	}
1.585     albertel 8523: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8524: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8525: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8526: 	}
                   8527:     }
1.738     albertel 8528:     # look for any posible extension_ match
                   8529:     foreach my $package (@extension) {
                   8530: 	my ($package,$pack_type)=@{$package};
                   8531: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8532: 	    return $packagetab{"$pack_type&$name&default"};
                   8533: 	}
                   8534: 	if (defined($packagetab{$package."&$name&default"})) {
                   8535: 	    return $packagetab{$package."&$name&default"};
                   8536: 	}
                   8537:     }
                   8538:     # look for a global default setting
                   8539:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8540: 	return $packagetab{"default&$name&default"};
                   8541:     }
1.395     albertel 8542:     return undef;
                   8543: }
                   8544: 
1.334     albertel 8545: sub add_prefix_and_part {
                   8546:     my ($prefix,$part)=@_;
                   8547:     my $keyroot;
                   8548:     if (defined($prefix) && $prefix !~ /^__/) {
                   8549: 	# prefix that has a part already
                   8550: 	$keyroot=$prefix;
                   8551:     } elsif (defined($prefix)) {
                   8552: 	# prefix that is missing a part
                   8553: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8554:     } else {
                   8555: 	# no prefix at all
                   8556: 	if (defined($part)) { $keyroot='_'.$part; }
                   8557:     }
                   8558:     return $keyroot;
                   8559: }
                   8560: 
1.71      www      8561: # ---------------------------------------------------------------- Get metadata
                   8562: 
1.599     albertel 8563: my %metaentry;
1.1070    www      8564: my %importedpartids;
1.71      www      8565: sub metadata {
1.176     www      8566:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8567:     $uri=&declutter($uri);
1.288     albertel 8568:     # if it is a non metadata possible uri return quickly
1.529     albertel 8569:     if (($uri eq '') || 
                   8570: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8571: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8572:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8573: 	return undef;
                   8574:     }
                   8575:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8576: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8577: 	return undef;
1.288     albertel 8578:     }
1.73      www      8579:     my $filename=$uri;
                   8580:     $uri=~s/\.meta$//;
1.172     www      8581: #
                   8582: # Is the metadata already cached?
1.177     www      8583: # Look at timestamp of caching
1.172     www      8584: # Everything is cached by the main uri, libraries are never directly cached
                   8585: #
1.428     albertel 8586:     if (!defined($liburi)) {
1.599     albertel 8587: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8588: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8589:     }
                   8590:     {
1.1069    www      8591: # Imported parts would go here
1.1070    www      8592:         my %importedids=();
                   8593:         my @origfileimportpartids=();
1.1069    www      8594:         my $importedparts=0;
1.172     www      8595: #
                   8596: # Is this a recursive call for a library?
                   8597: #
1.599     albertel 8598: #	if (! exists($metacache{$uri})) {
                   8599: #	    $metacache{$uri}={};
                   8600: #	}
1.924     albertel 8601: 	my $cachetime = 60*60;
1.171     www      8602:         if ($liburi) {
                   8603: 	    $liburi=&declutter($liburi);
                   8604:             $filename=$liburi;
1.401     bowersj2 8605:         } else {
1.599     albertel 8606: 	    &devalidate_cache_new('meta',$uri);
                   8607: 	    undef(%metaentry);
1.401     bowersj2 8608: 	}
1.140     www      8609:         my %metathesekeys=();
1.73      www      8610:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8611: 	my $metastring;
1.924     albertel 8612: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8613: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8614: 	    $metastring = 
1.929     albertel 8615: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8616: 					  ('grade_target' => 'meta'));
                   8617: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  8618: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8619:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8620: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8621: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8622: 	    $metastring=&getfile($file);
1.489     albertel 8623: 	}
1.208     albertel 8624:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8625:         my $token;
1.140     www      8626:         undef %metathesekeys;
1.71      www      8627:         while ($token=$parser->get_token) {
1.339     albertel 8628: 	    if ($token->[0] eq 'S') {
                   8629: 		if (defined($token->[2]->{'package'})) {
1.172     www      8630: #
                   8631: # This is a package - get package info
                   8632: #
1.339     albertel 8633: 		    my $package=$token->[2]->{'package'};
                   8634: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8635: 		    if (defined($token->[2]->{'id'})) { 
                   8636: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8637: 		    }
1.599     albertel 8638: 		    if ($metaentry{':packages'}) {
                   8639: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8640: 		    } else {
1.599     albertel 8641: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8642: 		    }
1.736     albertel 8643: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8644: 			my $part=$keyroot;
                   8645: 			$part=~s/^\_//;
1.736     albertel 8646: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8647: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8648: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8649: 			    # ignore package.tab specified default values
                   8650:                             # here &package_tab_default() will fetch those
                   8651: 			    if ($subp eq 'default') { next; }
1.736     albertel 8652: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8653: 			    my $unikey;
                   8654: 			    if ($pack =~ /_0$/) {
                   8655: 				$unikey='parameter_0_'.$name;
                   8656: 				$part=0;
                   8657: 			    } else {
                   8658: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8659: 			    }
1.339     albertel 8660: 			    if ($subp eq 'display') {
                   8661: 				$value.=' [Part: '.$part.']';
                   8662: 			    }
1.599     albertel 8663: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8664: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8665: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8666: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8667: 			    }
1.599     albertel 8668: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8669: 				$metaentry{':'.$unikey}=
                   8670: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8671: 			    }
1.339     albertel 8672: 			}
                   8673: 		    }
                   8674: 		} else {
1.172     www      8675: #
                   8676: # This is not a package - some other kind of start tag
1.339     albertel 8677: #
                   8678: 		    my $entry=$token->[1];
1.1068    www      8679: 		    my $unikey='';
1.175     www      8680: 
1.339     albertel 8681: 		    if ($entry eq 'import') {
1.175     www      8682: #
                   8683: # Importing a library here
1.339     albertel 8684: #
1.1067    www      8685:                         my $location=$parser->get_text('/import');
                   8686:                         my $dir=$filename;
                   8687:                         $dir=~s|[^/]*$||;
                   8688:                         $location=&filelocation($dir,$location);
1.1069    www      8689:                        
1.1068    www      8690:                         my $importmode=$token->[2]->{'importmode'};
                   8691:                         if ($importmode eq 'problem') {
1.1069    www      8692: # Import as problem/response
1.1068    www      8693:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8694:                         } elsif ($importmode eq 'part') {
                   8695: # Import as part(s)
1.1069    www      8696:                            $importedparts=1;
                   8697: # We need to get the original file and the imported file to get the part order correct
                   8698: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   8699: # Load and inspect original file
1.1070    www      8700:                            if ($#origfileimportpartids<0) {
                   8701:                               undef(%importedpartids);
                   8702:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   8703:                               my $origfile=&getfile($origfilelocation);
                   8704:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8705:                            }
                   8706: 
1.1069    www      8707: # Load and inspect imported file
                   8708:                            my $impfile=&getfile($location);
                   8709:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   8710:                            if ($#impfilepartids>=0) {
                   8711: # This problem had parts
1.1070    www      8712:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      8713:                            } else {
                   8714: # Importing by turning a single problem into a problem part
                   8715: # It gets the import-tags ID as part-ID
                   8716:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      8717:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      8718:                            }
1.1068    www      8719:                         } else {
                   8720: # Normal import
                   8721:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8722:                            if (defined($token->[2]->{'id'})) {
                   8723:                               $unikey.='_'.$token->[2]->{'id'};
                   8724:                            }
1.1067    www      8725:                         }
                   8726: 
1.339     albertel 8727: 			if ($depthcount<20) {
1.736     albertel 8728: 			    my $metadata = 
                   8729: 				&metadata($uri,'keys', $location,$unikey,
                   8730: 					  $depthcount+1);
                   8731: 			    foreach my $meta (split(',',$metadata)) {
                   8732: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8733: 				$metathesekeys{$meta}=1;
1.339     albertel 8734: 			    }
1.1068    www      8735: 			
                   8736:                         }
1.1067    www      8737: 		    } else {
                   8738: #
                   8739: # Not importing, some other kind of non-package, non-library start tag
                   8740: # 
                   8741:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8742:                         if (defined($token->[2]->{'id'})) {
                   8743:                             $unikey.='_'.$token->[2]->{'id'};
                   8744:                         }
1.339     albertel 8745: 			if (defined($token->[2]->{'name'})) { 
                   8746: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8747: 			}
                   8748: 			$metathesekeys{$unikey}=1;
1.736     albertel 8749: 			foreach my $param (@{$token->[3]}) {
                   8750: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8751: 				$token->[2]->{$param};
1.339     albertel 8752: 			}
                   8753: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8754: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8755: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8756: 		 # only ws inside the tag, and not in default, so use default
                   8757: 		 # as value
1.599     albertel 8758: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8759: 			} elsif ( $internaltext =~ /\S/ ) {
                   8760: 		  # something interesting inside the tag
                   8761: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8762: 			} else {
1.908     albertel 8763: 		  # no interesting values, don't set a default
1.339     albertel 8764: 			}
1.172     www      8765: # end of not-a-package not-a-library import
1.339     albertel 8766: 		    }
1.172     www      8767: # end of not-a-package start tag
1.339     albertel 8768: 		}
1.172     www      8769: # the next is the end of "start tag"
1.339     albertel 8770: 	    }
                   8771: 	}
1.483     albertel 8772: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8773: 	$extension = lc($extension);
                   8774: 	if ($extension eq 'htm') { $extension='html'; }
                   8775: 
1.737     albertel 8776: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8777: 	    #no specific packages #how's our extension
                   8778: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8779: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8780: 					 \%metathesekeys);
                   8781: 	}
1.883     albertel 8782: 
                   8783: 	if (!exists($metaentry{':packages'})
                   8784: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8785: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8786: 		#no specific packages well let's get default then
                   8787: 		if ($key!~/^default&/) { next; }
1.488     albertel 8788: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8789: 					     \%metathesekeys);
                   8790: 	    }
                   8791: 	}
1.338     www      8792: # are there custom rights to evaluate
1.599     albertel 8793: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8794: 
1.338     www      8795:     #
                   8796:     # Importing a rights file here
1.339     albertel 8797:     #
                   8798: 	    unless ($depthcount) {
1.599     albertel 8799: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8800: 		my $dir=$filename;
                   8801: 		$dir=~s|[^/]*$||;
                   8802: 		$location=&filelocation($dir,$location);
1.736     albertel 8803: 		my $rights_metadata =
                   8804: 		    &metadata($uri,'keys',$location,'_rights',
                   8805: 			      $depthcount+1);
                   8806: 		foreach my $rights (split(',',$rights_metadata)) {
                   8807: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8808: 		    $metathesekeys{$rights}=1;
1.339     albertel 8809: 		}
                   8810: 	    }
                   8811: 	}
1.737     albertel 8812: 	# uniqifiy package listing
                   8813: 	my %seen;
                   8814: 	my @uniq_packages =
                   8815: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8816: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8817: 
1.1070    www      8818:         if ($importedparts) {
                   8819: # We had imported parts and need to rebuild partorder
                   8820:            $metaentry{':partorder'}='';
                   8821:            $metathesekeys{'partorder'}=1;
                   8822:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   8823:                if ($origfileimportpartids[$index] eq 'part') {
                   8824: # original part, part of the problem
                   8825:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   8826:                } else {
                   8827: # we have imported parts at this position
                   8828:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   8829:                }
                   8830:            }
                   8831:            $metaentry{':partorder'}=~s/^\,//;
                   8832:         }
                   8833: 
1.737     albertel 8834: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8835: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8836: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8837: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8838: # this is the end of "was not already recently cached
1.71      www      8839:     }
1.599     albertel 8840:     return $metaentry{':'.$what};
1.261     albertel 8841: }
                   8842: 
1.488     albertel 8843: sub metadata_create_package_def {
1.483     albertel 8844:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8845:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8846:     if ($subp eq 'default') { next; }
                   8847:     
1.599     albertel 8848:     if (defined($metaentry{':packages'})) {
                   8849: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8850:     } else {
1.599     albertel 8851: 	$metaentry{':packages'}=$package;
1.483     albertel 8852:     }
                   8853:     my $value=$packagetab{$key};
                   8854:     my $unikey;
                   8855:     $unikey='parameter_0_'.$name;
1.599     albertel 8856:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8857:     $$metathesekeys{$unikey}=1;
1.599     albertel 8858:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8859: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8860:     }
1.599     albertel 8861:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8862: 	$metaentry{':'.$unikey}=
                   8863: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8864:     }
                   8865: }
                   8866: 
1.261     albertel 8867: sub metadata_generate_part0 {
                   8868:     my ($metadata,$metacache,$uri) = @_;
                   8869:     my %allnames;
1.737     albertel 8870:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8871: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8872: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8873: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8874: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8875: 	    $allnames{$name}=$part;
                   8876: 	  }
                   8877: 	}
                   8878:     }
                   8879:     foreach my $name (keys(%allnames)) {
                   8880:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8881:       my $key=":parameter_0_$name";
1.261     albertel 8882:       $$metacache{"$key.part"}='0';
                   8883:       $$metacache{"$key.name"}=$name;
1.428     albertel 8884:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8885: 					   $allnames{$name}.'_'.$name.
                   8886: 					   '.type'};
1.428     albertel 8887:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8888: 			     '.display'};
1.644     www      8889:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8890:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8891:       $$metacache{"$key.display"}=$olddis;
                   8892:     }
1.71      www      8893: }
                   8894: 
1.764     albertel 8895: # ------------------------------------------------------ Devalidate title cache
                   8896: 
                   8897: sub devalidate_title_cache {
                   8898:     my ($url)=@_;
                   8899:     if (!$env{'request.course.id'}) { return; }
                   8900:     my $symb=&symbread($url);
                   8901:     if (!$symb) { return; }
                   8902:     my $key=$env{'request.course.id'}."\0".$symb;
                   8903:     &devalidate_cache_new('title',$key);
                   8904: }
                   8905: 
1.1014    droeschl 8906: # ------------------------------------------------- Get the title of a course
                   8907: 
                   8908: sub current_course_title {
                   8909:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8910: }
1.301     www      8911: # ------------------------------------------------- Get the title of a resource
                   8912: 
                   8913: sub gettitle {
                   8914:     my $urlsymb=shift;
                   8915:     my $symb=&symbread($urlsymb);
1.534     albertel 8916:     if ($symb) {
1.620     albertel 8917: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8918: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8919: 	if (defined($cached)) { 
                   8920: 	    return $result;
                   8921: 	}
1.534     albertel 8922: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8923: 	my $title='';
1.907     albertel 8924: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8925: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8926: 	} else {
                   8927: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8928: 		    &GDBM_READER(),0640)) {
                   8929: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8930: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8931: 		untie(%bighash);
                   8932: 	    }
1.534     albertel 8933: 	}
                   8934: 	$title=~s/\&colon\;/\:/gs;
                   8935: 	if ($title) {
1.599     albertel 8936: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8937: 	}
                   8938: 	$urlsymb=$url;
                   8939:     }
                   8940:     my $title=&metadata($urlsymb,'title');
                   8941:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8942:     return $title;
1.301     www      8943: }
1.613     albertel 8944: 
1.614     albertel 8945: sub get_slot {
                   8946:     my ($which,$cnum,$cdom)=@_;
                   8947:     if (!$cnum || !$cdom) {
1.790     albertel 8948: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8949: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8950: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8951:     }
1.703     albertel 8952:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8953:     my %slotinfo;
                   8954:     if (exists($remembered{$key})) {
                   8955: 	$slotinfo{$which} = $remembered{$key};
                   8956:     } else {
                   8957: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8958: 	&Apache::lonhomework::showhash(%slotinfo);
                   8959: 	my ($tmp)=keys(%slotinfo);
                   8960: 	if ($tmp=~/^error:/) { return (); }
                   8961: 	$remembered{$key} = $slotinfo{$which};
                   8962:     }
1.616     albertel 8963:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8964: 	return %{$slotinfo{$which}};
                   8965:     }
                   8966:     return $slotinfo{$which};
1.614     albertel 8967: }
1.31      www      8968: # ------------------------------------------------- Update symbolic store links
                   8969: 
                   8970: sub symblist {
                   8971:     my ($mapname,%newhash)=@_;
1.438     www      8972:     $mapname=&deversion(&declutter($mapname));
1.31      www      8973:     my %hash;
1.620     albertel 8974:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8975:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8976:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8977: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8978: 		next if ($url eq 'last_known'
                   8979: 			 && $env{'form.no_update_last_known'});
                   8980: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8981: 						    $newhash{$url}->[1],
                   8982: 						    $newhash{$url}->[0]);
1.191     harris41 8983:             }
1.31      www      8984:             if (untie(%hash)) {
                   8985: 		return 'ok';
                   8986:             }
                   8987:         }
                   8988:     }
                   8989:     return 'error';
1.212     www      8990: }
                   8991: 
                   8992: # --------------------------------------------------------------- Verify a symb
                   8993: 
                   8994: sub symbverify {
1.510     www      8995:     my ($symb,$thisurl)=@_;
                   8996:     my $thisfn=$thisurl;
1.439     www      8997:     $thisfn=&declutter($thisfn);
1.215     www      8998: # direct jump to resource in page or to a sequence - will construct own symbs
                   8999:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9000: # check URL part
1.409     www      9001:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9002: 
1.431     www      9003:     unless ($url eq $thisfn) { return 0; }
1.213     www      9004: 
1.216     www      9005:     $symb=&symbclean($symb);
1.510     www      9006:     $thisurl=&deversion($thisurl);
1.439     www      9007:     $thisfn=&deversion($thisfn);
1.213     www      9008: 
                   9009:     my %bighash;
                   9010:     my $okay=0;
1.431     www      9011: 
1.620     albertel 9012:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9013:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9014:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9015:             $thisurl =~ s/\?.+$//;
                   9016:         }
1.510     www      9017:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9018:         unless ($ids) {
                   9019:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9020:             $ids=$bighash{$idkey};
1.216     www      9021:         }
                   9022:         if ($ids) {
                   9023: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9024: 	    foreach my $id (split(/\,/,$ids)) {
                   9025: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9026:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9027:                    $symb =~ s/\?.+$//;
                   9028:                }
1.216     www      9029:                if (
                   9030:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9031:    eq $symb) { 
1.620     albertel 9032: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9033: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9034:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9035: 		       $okay=1; 
                   9036: 		   }
                   9037: 	       }
1.216     www      9038: 	   }
                   9039:         }
1.213     www      9040: 	untie(%bighash);
                   9041:     }
                   9042:     return $okay;
1.31      www      9043: }
                   9044: 
1.210     www      9045: # --------------------------------------------------------------- Clean-up symb
                   9046: 
                   9047: sub symbclean {
                   9048:     my $symb=shift;
1.568     albertel 9049:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9050: # remove version from map
                   9051:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9052: 
1.210     www      9053: # remove version from URL
                   9054:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9055: 
1.507     www      9056: # remove wrapper
                   9057: 
1.510     www      9058:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9059:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9060:     return $symb;
1.409     www      9061: }
                   9062: 
                   9063: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9064: 
                   9065: sub encode_symb {
                   9066:     my ($map,$resid,$url)=@_;
                   9067:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9068: }
1.409     www      9069: 
                   9070: sub decode_symb {
1.568     albertel 9071:     my $symb=shift;
                   9072:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9073:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9074:     return (&fixversion($map),$resid,&fixversion($url));
                   9075: }
                   9076: 
                   9077: sub fixversion {
                   9078:     my $fn=shift;
1.609     banghart 9079:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9080:     my %bighash;
                   9081:     my $uri=&clutter($fn);
1.620     albertel 9082:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9083: # is this cached?
1.599     albertel 9084:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9085:     if (defined($cached)) { return $result; }
                   9086: # unfortunately not cached, or expired
1.620     albertel 9087:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9088: 	    &GDBM_READER(),0640)) {
                   9089:  	if ($bighash{'version_'.$uri}) {
                   9090:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9091:  	    unless (($version eq 'mostrecent') || 
                   9092: 		    ($version==&getversion($uri))) {
1.440     www      9093:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9094:  	    }
                   9095:  	}
                   9096:  	untie %bighash;
1.413     www      9097:     }
1.599     albertel 9098:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9099: }
                   9100: 
                   9101: sub deversion {
                   9102:     my $url=shift;
                   9103:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9104:     return $url;
1.210     www      9105: }
                   9106: 
1.31      www      9107: # ------------------------------------------------------ Return symb list entry
                   9108: 
                   9109: sub symbread {
1.249     www      9110:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9111:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9112:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9113: # no filename provided? try from environment
1.44      www      9114:     unless ($thisfn) {
1.620     albertel 9115:         if ($env{'request.symb'}) {
                   9116: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9117: 	}
1.620     albertel 9118: 	$thisfn=$env{'request.filename'};
1.44      www      9119:     }
1.569     albertel 9120:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9121: # is that filename actually a symb? Verify, clean, and return
                   9122:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9123: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9124: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9125: 	}
1.242     www      9126:     }
1.44      www      9127:     $thisfn=declutter($thisfn);
1.31      www      9128:     my %hash;
1.37      www      9129:     my %bighash;
                   9130:     my $syval='';
1.620     albertel 9131:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9132:         my $targetfn = $thisfn;
1.609     banghart 9133:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9134:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9135:         }
1.687     albertel 9136: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9137: 	    $targetfn=$1;
                   9138: 	}
1.620     albertel 9139:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9140:                       &GDBM_READER(),0640)) {
1.481     raeburn  9141: 	    $syval=$hash{$targetfn};
1.37      www      9142:             untie(%hash);
                   9143:         }
                   9144: # ---------------------------------------------------------- There was an entry
                   9145:         if ($syval) {
1.601     albertel 9146: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9147: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9148: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9149: 		    #return $env{$cache_str}='';
1.601     albertel 9150: 		#}    
                   9151: 		#$syval.=$1;
                   9152: 	    #}
1.37      www      9153:         } else {
                   9154: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9155:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9156:                             &GDBM_READER(),0640)) {
1.37      www      9157: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9158:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9159:               unless ($ids) { 
                   9160:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9161:               }
                   9162:               unless ($ids) {
                   9163: # alias?
                   9164: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9165:               }
1.37      www      9166:               if ($ids) {
                   9167: # ------------------------------------------------------------------- Has ID(s)
                   9168:                  my @possibilities=split(/\,/,$ids);
1.39      www      9169:                  if ($#possibilities==0) {
                   9170: # ----------------------------------------------- There is only one possibility
1.37      www      9171: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9172: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9173: 						    $resid,$thisfn);
1.249     www      9174:                  } elsif (!$donotrecurse) {
1.39      www      9175: # ------------------------------------------ There is more than one possibility
                   9176:                      my $realpossible=0;
1.800     albertel 9177:                      foreach my $id (@possibilities) {
                   9178: 			 my $file=$bighash{'src_'.$id};
1.39      www      9179:                          if (&allowed('bre',$file)) {
1.800     albertel 9180:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9181:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9182: 				$realpossible++;
1.626     albertel 9183:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9184: 						    $resid,$thisfn);
1.39      www      9185:                             }
                   9186: 			 }
1.191     harris41 9187:                      }
1.39      www      9188: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9189:                  } else {
                   9190:                      $syval='';
1.37      www      9191:                  }
                   9192: 	      }
                   9193:               untie(%bighash)
1.481     raeburn  9194:            }
1.31      www      9195:         }
1.62      www      9196:         if ($syval) {
1.620     albertel 9197: 	    return $env{$cache_str}=$syval;
1.62      www      9198:         }
1.31      www      9199:     }
1.949     raeburn  9200:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9201:     return $env{$cache_str}='';
1.31      www      9202: }
                   9203: 
                   9204: # ---------------------------------------------------------- Return random seed
                   9205: 
1.32      www      9206: sub numval {
                   9207:     my $txt=shift;
                   9208:     $txt=~tr/A-J/0-9/;
                   9209:     $txt=~tr/a-j/0-9/;
                   9210:     $txt=~tr/K-T/0-9/;
                   9211:     $txt=~tr/k-t/0-9/;
                   9212:     $txt=~tr/U-Z/0-5/;
                   9213:     $txt=~tr/u-z/0-5/;
                   9214:     $txt=~s/\D//g;
1.564     albertel 9215:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9216:     return int($txt);
1.368     albertel 9217: }
                   9218: 
1.484     albertel 9219: sub numval2 {
                   9220:     my $txt=shift;
                   9221:     $txt=~tr/A-J/0-9/;
                   9222:     $txt=~tr/a-j/0-9/;
                   9223:     $txt=~tr/K-T/0-9/;
                   9224:     $txt=~tr/k-t/0-9/;
                   9225:     $txt=~tr/U-Z/0-5/;
                   9226:     $txt=~tr/u-z/0-5/;
                   9227:     $txt=~s/\D//g;
                   9228:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9229:     my $total;
                   9230:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9231:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9232:     return int($total);
                   9233: }
                   9234: 
1.575     albertel 9235: sub numval3 {
                   9236:     use integer;
                   9237:     my $txt=shift;
                   9238:     $txt=~tr/A-J/0-9/;
                   9239:     $txt=~tr/a-j/0-9/;
                   9240:     $txt=~tr/K-T/0-9/;
                   9241:     $txt=~tr/k-t/0-9/;
                   9242:     $txt=~tr/U-Z/0-5/;
                   9243:     $txt=~tr/u-z/0-5/;
                   9244:     $txt=~s/\D//g;
                   9245:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9246:     my $total;
                   9247:     foreach my $val (@txts) { $total+=$val; }
                   9248:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9249:     return $total;
                   9250: }
                   9251: 
1.675     albertel 9252: sub digest {
                   9253:     my ($data)=@_;
                   9254:     my $digest=&Digest::MD5::md5($data);
                   9255:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9256:     my ($e,$f);
                   9257:     {
                   9258:         use integer;
                   9259:         $e=($a+$b);
                   9260:         $f=($c+$d);
                   9261:         if ($_64bit) {
                   9262:             $e=(($e<<32)>>32);
                   9263:             $f=(($f<<32)>>32);
                   9264:         }
                   9265:     }
                   9266:     if (wantarray) {
                   9267: 	return ($e,$f);
                   9268:     } else {
                   9269: 	my $g;
                   9270: 	{
                   9271: 	    use integer;
                   9272: 	    $g=($e+$f);
                   9273: 	    if ($_64bit) {
                   9274: 		$g=(($g<<32)>>32);
                   9275: 	    }
                   9276: 	}
                   9277: 	return $g;
                   9278:     }
                   9279: }
                   9280: 
1.368     albertel 9281: sub latest_rnd_algorithm_id {
1.675     albertel 9282:     return '64bit5';
1.366     albertel 9283: }
1.32      www      9284: 
1.503     albertel 9285: sub get_rand_alg {
                   9286:     my ($courseid)=@_;
1.790     albertel 9287:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9288:     if ($courseid) {
1.620     albertel 9289: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9290:     }
                   9291:     return &latest_rnd_algorithm_id();
                   9292: }
                   9293: 
1.562     albertel 9294: sub validCODE {
                   9295:     my ($CODE)=@_;
                   9296:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9297:     return 0;
                   9298: }
                   9299: 
1.491     albertel 9300: sub getCODE {
1.620     albertel 9301:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9302:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9303: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9304: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9305: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9306:     }
                   9307:     return undef;
                   9308: }
                   9309: 
1.31      www      9310: sub rndseed {
1.155     albertel 9311:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9312:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9313:     if (!defined($symb)) {
1.366     albertel 9314: 	unless ($symb=$wsymb) { return time; }
                   9315:     }
                   9316:     if (!$courseid) { $courseid=$wcourseid; }
                   9317:     if (!$domain) { $domain=$wdomain; }
                   9318:     if (!$username) { $username=$wusername }
1.503     albertel 9319:     my $which=&get_rand_alg();
1.1110    www      9320: 
1.491     albertel 9321:     if (defined(&getCODE())) {
1.675     albertel 9322: 	if ($which eq '64bit5') {
                   9323: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9324: 	} elsif ($which eq '64bit4') {
1.575     albertel 9325: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9326: 	} else {
                   9327: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9328: 	}
1.675     albertel 9329:     } elsif ($which eq '64bit5') {
                   9330: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9331:     } elsif ($which eq '64bit4') {
                   9332: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9333:     } elsif ($which eq '64bit3') {
                   9334: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9335:     } elsif ($which eq '64bit2') {
                   9336: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9337:     } elsif ($which eq '64bit') {
                   9338: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9339:     }
                   9340:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9341: }
                   9342: 
                   9343: sub rndseed_32bit {
                   9344:     my ($symb,$courseid,$domain,$username)=@_;
                   9345:     {
                   9346: 	use integer;
                   9347: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9348: 	my $symbseed=numval($symb) << 22;
                   9349: 	my $namechck=unpack("%32C*",$username) << 17;
                   9350: 	my $nameseed=numval($username) << 12;
                   9351: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9352: 	my $courseseed=unpack("%32C*",$courseid);
                   9353: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9354: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9355: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9356: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9357: 	return $num;
                   9358:     }
                   9359: }
                   9360: 
                   9361: sub rndseed_64bit {
                   9362:     my ($symb,$courseid,$domain,$username)=@_;
                   9363:     {
                   9364: 	use integer;
                   9365: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9366: 	my $symbseed=numval($symb) << 10;
                   9367: 	my $namechck=unpack("%32S*",$username);
                   9368: 	
                   9369: 	my $nameseed=numval($username) << 21;
                   9370: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9371: 	my $courseseed=unpack("%32S*",$courseid);
                   9372: 	
                   9373: 	my $num1=$symbchck+$symbseed+$namechck;
                   9374: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9375: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9376: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9377: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9378: 	return "$num1,$num2";
1.155     albertel 9379:     }
1.366     albertel 9380: }
                   9381: 
1.443     albertel 9382: sub rndseed_64bit2 {
                   9383:     my ($symb,$courseid,$domain,$username)=@_;
                   9384:     {
                   9385: 	use integer;
                   9386: 	# strings need to be an even # of cahracters long, it it is odd the
                   9387:         # last characters gets thrown away
                   9388: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9389: 	my $symbseed=numval($symb) << 10;
                   9390: 	my $namechck=unpack("%32S*",$username.' ');
                   9391: 	
                   9392: 	my $nameseed=numval($username) << 21;
1.501     albertel 9393: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9394: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9395: 	
                   9396: 	my $num1=$symbchck+$symbseed+$namechck;
                   9397: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9398: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9399: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9400: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9401: 	return "$num1,$num2";
                   9402:     }
                   9403: }
                   9404: 
                   9405: sub rndseed_64bit3 {
                   9406:     my ($symb,$courseid,$domain,$username)=@_;
                   9407:     {
                   9408: 	use integer;
                   9409: 	# strings need to be an even # of cahracters long, it it is odd the
                   9410:         # last characters gets thrown away
                   9411: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9412: 	my $symbseed=numval2($symb) << 10;
                   9413: 	my $namechck=unpack("%32S*",$username.' ');
                   9414: 	
                   9415: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9416: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9417: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9418: 	
                   9419: 	my $num1=$symbchck+$symbseed+$namechck;
                   9420: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9421: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9422: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9423: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9424: 	
1.503     albertel 9425: 	return "$num1:$num2";
1.443     albertel 9426:     }
                   9427: }
                   9428: 
1.575     albertel 9429: sub rndseed_64bit4 {
                   9430:     my ($symb,$courseid,$domain,$username)=@_;
                   9431:     {
                   9432: 	use integer;
                   9433: 	# strings need to be an even # of cahracters long, it it is odd the
                   9434:         # last characters gets thrown away
                   9435: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9436: 	my $symbseed=numval3($symb) << 10;
                   9437: 	my $namechck=unpack("%32S*",$username.' ');
                   9438: 	
                   9439: 	my $nameseed=numval3($username) << 21;
                   9440: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9441: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9442: 	
                   9443: 	my $num1=$symbchck+$symbseed+$namechck;
                   9444: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9445: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9446: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9447: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9448: 	
1.575     albertel 9449: 	return "$num1:$num2";
                   9450:     }
                   9451: }
                   9452: 
1.675     albertel 9453: sub rndseed_64bit5 {
                   9454:     my ($symb,$courseid,$domain,$username)=@_;
                   9455:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9456:     return "$num1:$num2";
                   9457: }
                   9458: 
1.366     albertel 9459: sub rndseed_CODE_64bit {
                   9460:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9461:     {
1.366     albertel 9462: 	use integer;
1.443     albertel 9463: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9464: 	my $symbseed=numval2($symb);
1.491     albertel 9465: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9466: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9467: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9468: 	my $num1=$symbseed+$CODEchck;
                   9469: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9470: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9471: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9472: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9473: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9474: 	return "$num1:$num2";
1.366     albertel 9475:     }
                   9476: }
                   9477: 
1.575     albertel 9478: sub rndseed_CODE_64bit4 {
                   9479:     my ($symb,$courseid,$domain,$username)=@_;
                   9480:     {
                   9481: 	use integer;
                   9482: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9483: 	my $symbseed=numval3($symb);
                   9484: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9485: 	my $CODEseed=numval3(&getCODE());
                   9486: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9487: 	my $num1=$symbseed+$CODEchck;
                   9488: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9489: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9490: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9491: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9492: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9493: 	return "$num1:$num2";
                   9494:     }
                   9495: }
                   9496: 
1.675     albertel 9497: sub rndseed_CODE_64bit5 {
                   9498:     my ($symb,$courseid,$domain,$username)=@_;
                   9499:     my $code = &getCODE();
                   9500:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9501:     return "$num1:$num2";
                   9502: }
                   9503: 
1.366     albertel 9504: sub setup_random_from_rndseed {
                   9505:     my ($rndseed)=@_;
1.503     albertel 9506:     if ($rndseed =~/([,:])/) {
                   9507: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9508: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9509:     } else {
                   9510: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9511:     }
1.36      albertel 9512: }
                   9513: 
1.474     albertel 9514: sub latest_receipt_algorithm_id {
1.835     albertel 9515:     return 'receipt3';
1.474     albertel 9516: }
                   9517: 
1.480     www      9518: sub recunique {
                   9519:     my $fucourseid=shift;
                   9520:     my $unique;
1.835     albertel 9521:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9522: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9523: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9524:     } else {
                   9525: 	$unique=$perlvar{'lonReceipt'};
                   9526:     }
                   9527:     return unpack("%32C*",$unique);
                   9528: }
                   9529: 
                   9530: sub recprefix {
                   9531:     my $fucourseid=shift;
                   9532:     my $prefix;
1.835     albertel 9533:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9534: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9535: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9536:     } else {
                   9537: 	$prefix=$perlvar{'lonHostID'};
                   9538:     }
                   9539:     return unpack("%32C*",$prefix);
                   9540: }
                   9541: 
1.76      www      9542: sub ireceipt {
1.474     albertel 9543:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9544: 
                   9545:     my $return =&recprefix($fucourseid).'-';
                   9546: 
                   9547:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9548: 	$env{'request.state'} eq 'construct') {
                   9549: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9550: 	return $return;
                   9551:     }
                   9552: 
1.76      www      9553:     my $cuname=unpack("%32C*",$funame);
                   9554:     my $cudom=unpack("%32C*",$fudom);
                   9555:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9556:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9557:     my $cunique=&recunique($fucourseid);
1.474     albertel 9558:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9559:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9560: 
1.790     albertel 9561: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9562: 			       
                   9563: 	$return.= ($cunique%$cuname+
                   9564: 		   $cunique%$cudom+
                   9565: 		   $cusymb%$cuname+
                   9566: 		   $cusymb%$cudom+
                   9567: 		   $cucourseid%$cuname+
                   9568: 		   $cucourseid%$cudom+
                   9569: 		   $cpart%$cuname+
                   9570: 		   $cpart%$cudom);
                   9571:     } else {
                   9572: 	$return.= ($cunique%$cuname+
                   9573: 		   $cunique%$cudom+
                   9574: 		   $cusymb%$cuname+
                   9575: 		   $cusymb%$cudom+
                   9576: 		   $cucourseid%$cuname+
                   9577: 		   $cucourseid%$cudom);
                   9578:     }
                   9579:     return $return;
1.76      www      9580: }
                   9581: 
                   9582: sub receipt {
1.474     albertel 9583:     my ($part)=@_;
1.790     albertel 9584:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9585:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9586: }
1.260     ng       9587: 
1.790     albertel 9588: sub whichuser {
                   9589:     my ($passedsymb)=@_;
                   9590:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9591:     if (defined($env{'form.grade_symb'})) {
                   9592: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9593: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9594: 	if (!$allowed &&
                   9595: 	    exists($env{'request.course.sec'}) &&
                   9596: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9597: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9598: 			      '/'.$env{'request.course.sec'});
                   9599: 	}
                   9600: 	if ($allowed) {
                   9601: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9602: 	    $courseid=$tmp_courseid;
                   9603: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9604: 	    ($name)=&get_env_multiple('form.grade_username');
                   9605: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9606: 	}
                   9607:     }
                   9608:     if (!$passedsymb) {
                   9609: 	$symb=&symbread();
                   9610:     } else {
                   9611: 	$symb=$passedsymb;
                   9612:     }
                   9613:     $courseid=$env{'request.course.id'};
                   9614:     $domain=$env{'user.domain'};
                   9615:     $name=$env{'user.name'};
                   9616:     if ($name eq 'public' && $domain eq 'public') {
                   9617: 	if (!defined($env{'form.username'})) {
                   9618: 	    $env{'form.username'}.=time.rand(10000000);
                   9619: 	}
                   9620: 	$name.=$env{'form.username'};
                   9621:     }
                   9622:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9623: 
                   9624: }
                   9625: 
1.36      albertel 9626: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9627: # returns either the contents of the file or 
                   9628: # -1 if the file doesn't exist
1.481     raeburn  9629: #
                   9630: # if the target is a file that was uploaded via DOCS, 
                   9631: # a check will be made to see if a current copy exists on the local server,
                   9632: # if it does this will be served, otherwise a copy will be retrieved from
                   9633: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9634: # the local server.   
1.472     albertel 9635: 
1.36      albertel 9636: sub getfile {
1.538     albertel 9637:     my ($file) = @_;
1.609     banghart 9638:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9639:     &repcopy($file);
                   9640:     return &readfile($file);
                   9641: }
                   9642: 
                   9643: sub repcopy_userfile {
                   9644:     my ($file)=@_;
1.609     banghart 9645:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9646:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9647:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9648: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9649:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9650:     if (-e "$file") {
1.828     www      9651: # we already have a local copy, check it out
1.538     albertel 9652: 	my @fileinfo = stat($file);
1.828     www      9653: 	my $rtncode;
                   9654: 	my $info;
1.538     albertel 9655: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9656: 	if ($lwpresp ne 'ok') {
1.828     www      9657: # there is no such file anymore, even though we had a local copy
1.482     albertel 9658: 	    if ($rtncode eq '404') {
1.538     albertel 9659: 		unlink($file);
1.482     albertel 9660: 	    }
                   9661: 	    return -1;
                   9662: 	}
                   9663: 	if ($info < $fileinfo[9]) {
1.828     www      9664: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9665: 	    return 'ok';
1.828     www      9666: 	} else {
                   9667: # the file is outdated, get rid of it
                   9668: 	    unlink($file);
1.482     albertel 9669: 	}
1.828     www      9670:     }
                   9671: # one way or the other, at this point, we don't have the file
                   9672: # construct the correct path for the file
                   9673:     my @parts = ($cdom,$cnum); 
                   9674:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9675: 	push @parts, split(/\//,$1);
                   9676:     }
                   9677:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9678:     foreach my $part (@parts) {
                   9679: 	$path .= '/'.$part;
                   9680: 	if (!-e $path) {
                   9681: 	    mkdir($path,0770);
1.482     albertel 9682: 	}
                   9683:     }
1.828     www      9684: # now the path exists for sure
                   9685: # get a user agent
                   9686:     my $ua=new LWP::UserAgent;
                   9687:     my $transferfile=$file.'.in.transfer';
                   9688: # FIXME: this should flock
                   9689:     if (-e $transferfile) { return 'ok'; }
                   9690:     my $request;
                   9691:     $uri=~s/^\///;
1.980     raeburn  9692:     my $homeserver = &homeserver($cnum,$cdom);
                   9693:     my $protocol = $protocol{$homeserver};
                   9694:     $protocol = 'http' if ($protocol ne 'https');
                   9695:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9696:     my $response=$ua->request($request,$transferfile);
                   9697: # did it work?
                   9698:     if ($response->is_error()) {
                   9699: 	unlink($transferfile);
                   9700: 	&logthis("Userfile repcopy failed for $uri");
                   9701: 	return -1;
                   9702:     }
                   9703: # worked, rename the transfer file
                   9704:     rename($transferfile,$file);
1.607     raeburn  9705:     return 'ok';
1.481     raeburn  9706: }
                   9707: 
1.517     albertel 9708: sub tokenwrapper {
                   9709:     my $uri=shift;
1.980     raeburn  9710:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9711:     $uri=~s|^/||;
1.620     albertel 9712:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9713:     my $token=$1;
1.552     albertel 9714:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9715:     if ($udom && $uname && $file) {
                   9716: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9717:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9718:         my $homeserver = &homeserver($uname,$udom);
                   9719:         my $protocol = $protocol{$homeserver};
                   9720:         $protocol = 'http' if ($protocol ne 'https');
                   9721:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9722:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9723:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9724:     } else {
                   9725:         return '/adm/notfound.html';
                   9726:     }
                   9727: }
                   9728: 
1.828     www      9729: # call with reqtype HEAD: get last modification time
                   9730: # call with reqtype GET: get the file contents
                   9731: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9732: #
1.481     raeburn  9733: sub getuploaded {
                   9734:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9735:     $uri=~s/^\///;
1.980     raeburn  9736:     my $homeserver = &homeserver($cnum,$cdom);
                   9737:     my $protocol = $protocol{$homeserver};
                   9738:     $protocol = 'http' if ($protocol ne 'https');
                   9739:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9740:     my $ua=new LWP::UserAgent;
                   9741:     my $request=new HTTP::Request($reqtype,$uri);
                   9742:     my $response=$ua->request($request);
                   9743:     $$rtncode = $response->code;
1.482     albertel 9744:     if (! $response->is_success()) {
                   9745: 	return 'failed';
                   9746:     }      
                   9747:     if ($reqtype eq 'HEAD') {
1.486     www      9748: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9749:     } elsif ($reqtype eq 'GET') {
                   9750: 	$$info = $response->content;
1.472     albertel 9751:     }
1.482     albertel 9752:     return 'ok';
1.36      albertel 9753: }
                   9754: 
1.481     raeburn  9755: sub readfile {
                   9756:     my $file = shift;
                   9757:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9758:     my $fh;
                   9759:     open($fh,"<$file");
                   9760:     my $a='';
1.800     albertel 9761:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9762:     return $a;
                   9763: }
                   9764: 
1.36      albertel 9765: sub filelocation {
1.590     banghart 9766:     my ($dir,$file) = @_;
                   9767:     my $location;
                   9768:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9769: 
                   9770:     if ($file =~ m-^/adm/-) {
                   9771: 	$file=~s-^/adm/wrapper/-/-;
                   9772: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9773:     }
1.882     albertel 9774: 
1.590     banghart 9775:     if ($file=~m:^/~:) { # is a contruction space reference
                   9776:         $location = $file;
                   9777:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9778:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9779: 	# is a correct contruction space reference
                   9780:         $location = $file;
1.956     raeburn  9781:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9782:         $location = $file;
1.609     banghart 9783:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9784:         my ($udom,$uname,$filename)=
1.811     albertel 9785:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9786:         my $home=&homeserver($uname,$udom);
                   9787:         my $is_me=0;
                   9788:         my @ids=&current_machine_ids();
                   9789:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9790:         if ($is_me) {
1.955     raeburn  9791:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9792:         } else {
                   9793:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9794:   	      $udom.'/'.$uname.'/'.$filename;
                   9795:         }
1.882     albertel 9796:     } elsif ($file =~ m-^/adm/-) {
                   9797: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9798:     } else {
                   9799:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9800:         $file=~s:^/res/:/:;
                   9801:         if ( !( $file =~ m:^/:) ) {
                   9802:             $location = $dir. '/'.$file;
                   9803:         } else {
                   9804:             $location = '/home/httpd/html/res'.$file;
                   9805:         }
1.59      albertel 9806:     }
1.590     banghart 9807:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9808:     while ($location=~m{/\.\./}) {
                   9809: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9810: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9811: 	} else {
                   9812: 	    $location=~ s{/\.\./}{/}g;
                   9813: 	}
                   9814:     } #remove dir/..
1.590     banghart 9815:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9816:     return $location;
1.46      www      9817: }
1.36      albertel 9818: 
1.46      www      9819: sub hreflocation {
                   9820:     my ($dir,$file)=@_;
1.980     raeburn  9821:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9822: 	$file=filelocation($dir,$file);
1.700     albertel 9823:     } elsif ($file=~m-^/adm/-) {
                   9824: 	$file=~s-^/adm/wrapper/-/-;
                   9825: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9826:     }
                   9827:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9828: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9829:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9830: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9831:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9832: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9833: 	    -/uploaded/$1/$2/-x;
1.46      www      9834:     }
1.913     albertel 9835:     if ($file=~ m{^/userfiles/}) {
                   9836: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9837:     }
1.462     albertel 9838:     return $file;
1.465     albertel 9839: }
                   9840: 
                   9841: sub current_machine_domains {
1.853     albertel 9842:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9843: }
                   9844: 
                   9845: sub machine_domains {
                   9846:     my ($hostname) = @_;
1.465     albertel 9847:     my @domains;
1.838     albertel 9848:     my %hostname = &all_hostnames();
1.465     albertel 9849:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9850: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9851: 	if ($hostname eq $name) {
1.844     albertel 9852: 	    push(@domains,&host_domain($id));
1.465     albertel 9853: 	}
                   9854:     }
                   9855:     return @domains;
                   9856: }
                   9857: 
                   9858: sub current_machine_ids {
1.853     albertel 9859:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9860: }
                   9861: 
                   9862: sub machine_ids {
                   9863:     my ($hostname) = @_;
                   9864:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9865:     my @ids;
1.888     albertel 9866:     my %name_to_host = &all_names();
1.889     albertel 9867:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9868: 	return @{ $name_to_host{$hostname} };
                   9869:     }
                   9870:     return;
1.31      www      9871: }
                   9872: 
1.824     raeburn  9873: sub additional_machine_domains {
                   9874:     my @domains;
                   9875:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9876:     while( my $line = <$fh>) {
                   9877:         $line =~ s/\s//g;
                   9878:         push(@domains,$line);
                   9879:     }
                   9880:     return @domains;
                   9881: }
                   9882: 
                   9883: sub default_login_domain {
                   9884:     my $domain = $perlvar{'lonDefDomain'};
                   9885:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9886:     foreach my $posdom (&current_machine_domains(),
                   9887:                         &additional_machine_domains()) {
                   9888:         if (lc($posdom) eq lc($testdomain)) {
                   9889:             $domain=$posdom;
                   9890:             last;
                   9891:         }
                   9892:     }
                   9893:     return $domain;
                   9894: }
                   9895: 
1.31      www      9896: # ------------------------------------------------------------- Declutters URLs
                   9897: 
                   9898: sub declutter {
                   9899:     my $thisfn=shift;
1.569     albertel 9900:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9901:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9902:     $thisfn=~s/^\///;
1.697     albertel 9903:     $thisfn=~s|^adm/wrapper/||;
                   9904:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9905:     $thisfn=~s/^res\///;
1.1032    raeburn  9906:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9907:         $thisfn=~s/\?.+$//;
                   9908:     }
1.268     www      9909:     return $thisfn;
                   9910: }
                   9911: 
                   9912: # ------------------------------------------------------------- Clutter up URLs
                   9913: 
                   9914: sub clutter {
                   9915:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9916:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9917: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9918:        $thisfn='/res'.$thisfn; 
                   9919:     }
1.1031    raeburn  9920:     if ($thisfn !~m|^/adm|) {
                   9921: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9922: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9923: 	} else {
                   9924: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9925: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9926: 	    if ($embstyle eq 'ssi'
                   9927: 		|| ($embstyle eq 'hdn')
                   9928: 		|| ($embstyle eq 'rat')
                   9929: 		|| ($embstyle eq 'prv')
                   9930: 		|| ($embstyle eq 'ign')) {
                   9931: 		#do nothing with these
                   9932: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9933: 		|| ($embstyle eq 'emb')
                   9934: 		|| ($embstyle eq 'wrp')) {
                   9935: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9936: 	    } elsif ($embstyle eq 'unk'
                   9937: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9938: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9939: 	    } else {
1.718     www      9940: #		&logthis("Got a blank emb style");
1.695     albertel 9941: 	    }
1.694     albertel 9942: 	}
                   9943:     }
1.31      www      9944:     return $thisfn;
1.12      www      9945: }
                   9946: 
1.787     albertel 9947: sub clutter_with_no_wrapper {
                   9948:     my $uri = &clutter(shift);
                   9949:     if ($uri =~ m-^/adm/-) {
                   9950: 	$uri =~ s-^/adm/wrapper/-/-;
                   9951: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9952:     }
                   9953:     return $uri;
                   9954: }
                   9955: 
1.557     albertel 9956: sub freeze_escape {
                   9957:     my ($value)=@_;
                   9958:     if (ref($value)) {
                   9959: 	$value=&nfreeze($value);
                   9960: 	return '__FROZEN__'.&escape($value);
                   9961:     }
                   9962:     return &escape($value);
                   9963: }
                   9964: 
1.11      www      9965: 
1.557     albertel 9966: sub thaw_unescape {
                   9967:     my ($value)=@_;
                   9968:     if ($value =~ /^__FROZEN__/) {
                   9969: 	substr($value,0,10,undef);
                   9970: 	$value=&unescape($value);
                   9971: 	return &thaw($value);
                   9972:     }
                   9973:     return &unescape($value);
                   9974: }
                   9975: 
1.436     albertel 9976: sub correct_line_ends {
                   9977:     my ($result)=@_;
                   9978:     $$result =~s/\r\n/\n/mg;
                   9979:     $$result =~s/\r/\n/mg;
1.415     albertel 9980: }
1.1       albertel 9981: # ================================================================ Main Program
                   9982: 
1.184     www      9983: sub goodbye {
1.204     albertel 9984:    &logthis("Starting Shut down");
1.443     albertel 9985: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9986:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9987: #converted
1.599     albertel 9988: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9989:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9990: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9991: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9992: #1.1 only
1.870     albertel 9993: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9994: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9995: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9996: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9997:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9998:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9999:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10000:    &flushcourselogs();
                   10001:    &logthis("Shutting down");
                   10002: }
                   10003: 
1.852     albertel 10004: sub get_dns {
1.869     albertel 10005:     my ($url,$func,$ignore_cache) = @_;
                   10006:     if (!$ignore_cache) {
                   10007: 	my ($content,$cached)=
                   10008: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10009: 	if ($cached) {
                   10010: 	    &$func($content);
                   10011: 	    return;
                   10012: 	}
                   10013:     }
                   10014: 
                   10015:     my %alldns;
1.852     albertel 10016:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10017:     foreach my $dns (<$config>) {
                   10018: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10019:         my $line = $1;
                   10020:         my ($host,$protocol) = split(/:/,$line);
                   10021:         if ($protocol ne 'https') {
                   10022:             $protocol = 'http';
                   10023:         }
                   10024: 	$alldns{$host} = $protocol;
1.869     albertel 10025:     }
                   10026:     while (%alldns) {
                   10027: 	my ($dns) = keys(%alldns);
1.852     albertel 10028: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10029: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10030: 	my $response=$ua->request($request);
1.979     raeburn  10031:         delete($alldns{$dns});
1.852     albertel 10032: 	next if ($response->is_error());
                   10033: 	my @content = split("\n",$response->content);
1.869     albertel 10034: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10035: 	&$func(\@content);
1.869     albertel 10036: 	return;
1.852     albertel 10037:     }
                   10038:     close($config);
1.871     albertel 10039:     my $which = (split('/',$url))[3];
                   10040:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10041:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10042:     my @content = <$config>;
                   10043:     &$func(\@content);
                   10044:     return;
1.852     albertel 10045: }
1.327     albertel 10046: # ------------------------------------------------------------ Read domain file
                   10047: {
1.852     albertel 10048:     my $loaded;
1.846     albertel 10049:     my %domain;
                   10050: 
1.852     albertel 10051:     sub parse_domain_tab {
                   10052: 	my ($lines) = @_;
                   10053: 	foreach my $line (@$lines) {
                   10054: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10055: 
1.846     albertel 10056: 	    chomp($line);
1.852     albertel 10057: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10058: 	    my %this_domain;
                   10059: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10060: 			       'lang_def', 'city', 'longi', 'lati',
                   10061: 			       'primary') {
                   10062: 		$this_domain{$field} = shift(@elements);
                   10063: 	    }
                   10064: 	    $domain{$name} = \%this_domain;
1.852     albertel 10065: 	}
                   10066:     }
1.864     albertel 10067: 
                   10068:     sub reset_domain_info {
                   10069: 	undef($loaded);
                   10070: 	undef(%domain);
                   10071:     }
                   10072: 
1.852     albertel 10073:     sub load_domain_tab {
1.869     albertel 10074: 	my ($ignore_cache) = @_;
                   10075: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10076: 	my $fh;
                   10077: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10078: 	    my @lines = <$fh>;
                   10079: 	    &parse_domain_tab(\@lines);
1.448     albertel 10080: 	}
1.852     albertel 10081: 	close($fh);
                   10082: 	$loaded = 1;
1.327     albertel 10083:     }
1.846     albertel 10084: 
                   10085:     sub domain {
1.852     albertel 10086: 	&load_domain_tab() if (!$loaded);
                   10087: 
1.846     albertel 10088: 	my ($name,$what) = @_;
                   10089: 	return if ( !exists($domain{$name}) );
                   10090: 
                   10091: 	if (!$what) {
                   10092: 	    return $domain{$name}{'description'};
                   10093: 	}
                   10094: 	return $domain{$name}{$what};
                   10095:     }
1.974     raeburn  10096: 
                   10097:     sub domain_info {
                   10098:         &load_domain_tab() if (!$loaded);
                   10099:         return %domain;
                   10100:     }
                   10101: 
1.327     albertel 10102: }
                   10103: 
                   10104: 
1.1       albertel 10105: # ------------------------------------------------------------- Read hosts file
                   10106: {
1.838     albertel 10107:     my %hostname;
1.844     albertel 10108:     my %hostdom;
1.845     albertel 10109:     my %libserv;
1.852     albertel 10110:     my $loaded;
1.888     albertel 10111:     my %name_to_host;
1.1074    raeburn  10112:     my %internetdom;
1.1107    raeburn  10113:     my %LC_dns_serv;
1.852     albertel 10114: 
                   10115:     sub parse_hosts_tab {
                   10116: 	my ($file) = @_;
                   10117: 	foreach my $configline (@$file) {
                   10118: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10119:             chomp($configline);
                   10120: 	    if ($configline =~ /^\^/) {
                   10121:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10122:                     $LC_dns_serv{$1} = 1;
                   10123:                 }
                   10124:                 next;
                   10125:             }
1.1074    raeburn  10126: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10127: 	    $name=~s/\s//g;
                   10128: 	    if ($id && $domain && $role && $name) {
                   10129: 		$hostname{$id}=$name;
1.888     albertel 10130: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10131: 		$hostdom{$id}=$domain;
                   10132: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10133:                 if (defined($protocol)) {
                   10134:                     if ($protocol eq 'https') {
                   10135:                         $protocol{$id} = $protocol;
                   10136:                     } else {
                   10137:                         $protocol{$id} = 'http'; 
                   10138:                     }
1.968     raeburn  10139:                 } else {
1.969     raeburn  10140:                     $protocol{$id} = 'http';
1.968     raeburn  10141:                 }
1.1074    raeburn  10142:                 if (defined($intdom)) {
                   10143:                     $internetdom{$id} = $intdom;
                   10144:                 }
1.852     albertel 10145: 	    }
                   10146: 	}
                   10147:     }
1.864     albertel 10148:     
                   10149:     sub reset_hosts_info {
1.897     albertel 10150: 	&purge_remembered();
1.864     albertel 10151: 	&reset_domain_info();
                   10152: 	&reset_hosts_ip_info();
1.892     albertel 10153: 	undef(%name_to_host);
1.864     albertel 10154: 	undef(%hostname);
                   10155: 	undef(%hostdom);
                   10156: 	undef(%libserv);
                   10157: 	undef($loaded);
                   10158:     }
1.1       albertel 10159: 
1.852     albertel 10160:     sub load_hosts_tab {
1.869     albertel 10161: 	my ($ignore_cache) = @_;
                   10162: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10163: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10164: 	my @config = <$config>;
                   10165: 	&parse_hosts_tab(\@config);
                   10166: 	close($config);
                   10167: 	$loaded=1;
1.1       albertel 10168:     }
1.852     albertel 10169: 
1.838     albertel 10170:     sub hostname {
1.852     albertel 10171: 	&load_hosts_tab() if (!$loaded);
                   10172: 
1.838     albertel 10173: 	my ($lonid) = @_;
                   10174: 	return $hostname{$lonid};
                   10175:     }
1.845     albertel 10176: 
1.838     albertel 10177:     sub all_hostnames {
1.852     albertel 10178: 	&load_hosts_tab() if (!$loaded);
                   10179: 
1.838     albertel 10180: 	return %hostname;
                   10181:     }
1.845     albertel 10182: 
1.888     albertel 10183:     sub all_names {
                   10184: 	&load_hosts_tab() if (!$loaded);
                   10185: 
                   10186: 	return %name_to_host;
                   10187:     }
                   10188: 
1.974     raeburn  10189:     sub all_host_domain {
                   10190:         &load_hosts_tab() if (!$loaded);
                   10191:         return %hostdom;
                   10192:     }
                   10193: 
1.845     albertel 10194:     sub is_library {
1.852     albertel 10195: 	&load_hosts_tab() if (!$loaded);
                   10196: 
1.845     albertel 10197: 	return exists($libserv{$_[0]});
                   10198:     }
                   10199: 
                   10200:     sub all_library {
1.852     albertel 10201: 	&load_hosts_tab() if (!$loaded);
                   10202: 
1.845     albertel 10203: 	return %libserv;
                   10204:     }
                   10205: 
1.1062    droeschl 10206:     sub unique_library {
                   10207: 	#2x reverse removes all hostnames that appear more than once
                   10208:         my %unique = reverse &all_library();
                   10209:         return reverse %unique;
                   10210:     }
                   10211: 
1.841     albertel 10212:     sub get_servers {
1.852     albertel 10213: 	&load_hosts_tab() if (!$loaded);
                   10214: 
1.841     albertel 10215: 	my ($domain,$type) = @_;
                   10216: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10217: 	                                          : %hostname;
                   10218: 	my %result;
1.842     albertel 10219: 	if (ref($domain) eq 'ARRAY') {
                   10220: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10221: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10222: 		    $result{$host} = $hostname;
                   10223: 		}
                   10224: 	    }
                   10225: 	} else {
                   10226: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10227: 		if ($hostdom{$host} eq $domain) {
                   10228: 		    $result{$host} = $hostname;
                   10229: 		}
1.841     albertel 10230: 	    }
                   10231: 	}
                   10232: 	return %result;
                   10233:     }
1.845     albertel 10234: 
1.1062    droeschl 10235:     sub get_unique_servers {
                   10236:         my %unique = reverse &get_servers(@_);
                   10237: 	return reverse %unique;
                   10238:     }
                   10239: 
1.844     albertel 10240:     sub host_domain {
1.852     albertel 10241: 	&load_hosts_tab() if (!$loaded);
                   10242: 
1.844     albertel 10243: 	my ($lonid) = @_;
                   10244: 	return $hostdom{$lonid};
                   10245:     }
                   10246: 
1.841     albertel 10247:     sub all_domains {
1.852     albertel 10248: 	&load_hosts_tab() if (!$loaded);
                   10249: 
1.841     albertel 10250: 	my %seen;
                   10251: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10252: 	return @uniq;
                   10253:     }
1.1074    raeburn  10254: 
                   10255:     sub internet_dom {
                   10256:         &load_hosts_tab() if (!$loaded);
                   10257: 
                   10258:         my ($lonid) = @_;
                   10259:         return $internetdom{$lonid};
                   10260:     }
1.1107    raeburn  10261: 
                   10262:     sub is_LC_dns {
                   10263:         &load_hosts_tab() if (!$loaded);
                   10264: 
                   10265:         my ($hostname) = @_;
                   10266:         return exists($LC_dns_serv{$hostname});
                   10267:     }
                   10268: 
1.1       albertel 10269: }
                   10270: 
1.847     albertel 10271: { 
                   10272:     my %iphost;
1.856     albertel 10273:     my %name_to_ip;
                   10274:     my %lonid_to_ip;
1.869     albertel 10275: 
1.847     albertel 10276:     sub get_hosts_from_ip {
                   10277: 	my ($ip) = @_;
                   10278: 	my %iphosts = &get_iphost();
                   10279: 	if (ref($iphosts{$ip})) {
                   10280: 	    return @{$iphosts{$ip}};
                   10281: 	}
                   10282: 	return;
1.839     albertel 10283:     }
1.864     albertel 10284:     
                   10285:     sub reset_hosts_ip_info {
                   10286: 	undef(%iphost);
                   10287: 	undef(%name_to_ip);
                   10288: 	undef(%lonid_to_ip);
                   10289:     }
1.856     albertel 10290: 
                   10291:     sub get_host_ip {
                   10292: 	my ($lonid) = @_;
                   10293: 	if (exists($lonid_to_ip{$lonid})) {
                   10294: 	    return $lonid_to_ip{$lonid};
                   10295: 	}
                   10296: 	my $name=&hostname($lonid);
                   10297:    	my $ip = gethostbyname($name);
                   10298: 	return if (!$ip || length($ip) ne 4);
                   10299: 	$ip=inet_ntoa($ip);
                   10300: 	$name_to_ip{$name}   = $ip;
                   10301: 	$lonid_to_ip{$lonid} = $ip;
                   10302: 	return $ip;
                   10303:     }
1.847     albertel 10304:     
                   10305:     sub get_iphost {
1.869     albertel 10306: 	my ($ignore_cache) = @_;
1.894     albertel 10307: 
1.869     albertel 10308: 	if (!$ignore_cache) {
                   10309: 	    if (%iphost) {
                   10310: 		return %iphost;
                   10311: 	    }
                   10312: 	    my ($ip_info,$cached)=
                   10313: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10314: 	    if ($cached) {
                   10315: 		%iphost      = %{$ip_info->[0]};
                   10316: 		%name_to_ip  = %{$ip_info->[1]};
                   10317: 		%lonid_to_ip = %{$ip_info->[2]};
                   10318: 		return %iphost;
                   10319: 	    }
                   10320: 	}
1.894     albertel 10321: 
                   10322: 	# get yesterday's info for fallback
                   10323: 	my %old_name_to_ip;
                   10324: 	my ($ip_info,$cached)=
                   10325: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10326: 	if ($cached) {
                   10327: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10328: 	}
                   10329: 
1.888     albertel 10330: 	my %name_to_host = &all_names();
                   10331: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10332: 	    my $ip;
                   10333: 	    if (!exists($name_to_ip{$name})) {
                   10334: 		$ip = gethostbyname($name);
                   10335: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10336: 		    if (defined($old_name_to_ip{$name})) {
                   10337: 			$ip = $old_name_to_ip{$name};
                   10338: 			&logthis("Can't find $name defaulting to old $ip");
                   10339: 		    } else {
                   10340: 			&logthis("Name $name no IP found");
                   10341: 			next;
                   10342: 		    }
                   10343: 		} else {
                   10344: 		    $ip=inet_ntoa($ip);
1.847     albertel 10345: 		}
                   10346: 		$name_to_ip{$name} = $ip;
                   10347: 	    } else {
                   10348: 		$ip = $name_to_ip{$name};
1.653     albertel 10349: 	    }
1.888     albertel 10350: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10351: 		$lonid_to_ip{$id} = $ip;
                   10352: 	    }
                   10353: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10354: 	}
1.869     albertel 10355: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10356: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10357: 				      48*60*60);
1.869     albertel 10358: 
1.847     albertel 10359: 	return %iphost;
1.598     albertel 10360:     }
                   10361: 
1.992     raeburn  10362:     #
                   10363:     #  Given a DNS returns the loncapa host name for that DNS 
                   10364:     # 
                   10365:     sub host_from_dns {
                   10366:         my ($dns) = @_;
                   10367:         my @hosts;
                   10368:         my $ip;
                   10369: 
1.993     raeburn  10370:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10371:             $ip = $name_to_ip{$dns};
                   10372:         }
                   10373:         if (!$ip) {
                   10374:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10375:             if (length($ip) == 4) { 
                   10376: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10377:             }
                   10378:         }
                   10379:         if ($ip) {
                   10380: 	    @hosts = get_hosts_from_ip($ip);
                   10381: 	    return $hosts[0];
                   10382:         }
                   10383:         return undef;
1.986     foxr     10384:     }
1.992     raeburn  10385: 
1.1074    raeburn  10386:     sub get_internet_names {
                   10387:         my ($lonid) = @_;
                   10388:         return if ($lonid eq '');
                   10389:         my ($idnref,$cached)=
                   10390:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10391:         if ($cached) {
                   10392:             return $idnref;
                   10393:         }
                   10394:         my $ip = &get_host_ip($lonid);
                   10395:         my @hosts = &get_hosts_from_ip($ip);
                   10396:         my %iphost = &get_iphost();
                   10397:         my (@idns,%seen);
                   10398:         foreach my $id (@hosts) {
                   10399:             my $dom = &host_domain($id);
                   10400:             my $prim_id = &domain($dom,'primary');
                   10401:             my $prim_ip = &get_host_ip($prim_id);
                   10402:             next if ($seen{$prim_ip});
                   10403:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10404:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10405:                     my $intdom = &internet_dom($id);
                   10406:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10407:                         push(@idns,$intdom);
                   10408:                     }
                   10409:                 }
                   10410:             }
                   10411:             $seen{$prim_ip} = 1;
                   10412:         }
                   10413:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10414:     }
                   10415: 
1.986     foxr     10416: }
                   10417: 
1.1079    raeburn  10418: sub all_loncaparevs {
                   10419:     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);
                   10420: }
                   10421: 
1.862     albertel 10422: BEGIN {
                   10423: 
                   10424: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10425:     unless ($readit) {
                   10426: {
                   10427:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10428:     %perlvar = (%perlvar,%{$configvars});
                   10429: }
                   10430: 
                   10431: 
1.1       albertel 10432: # ------------------------------------------------------ Read spare server file
                   10433: {
1.448     albertel 10434:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10435: 
                   10436:     while (my $configline=<$config>) {
                   10437:        chomp($configline);
1.284     matthew  10438:        if ($configline) {
1.784     albertel 10439: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10440: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10441: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10442:        }
                   10443:     }
1.448     albertel 10444:     close($config);
1.1       albertel 10445: }
1.11      www      10446: # ------------------------------------------------------------ Read permissions
                   10447: {
1.448     albertel 10448:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10449: 
                   10450:     while (my $configline=<$config>) {
1.448     albertel 10451: 	chomp($configline);
                   10452: 	if ($configline) {
                   10453: 	    my ($role,$perm)=split(/ /,$configline);
                   10454: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10455: 	}
1.11      www      10456:     }
1.448     albertel 10457:     close($config);
1.11      www      10458: }
                   10459: 
                   10460: # -------------------------------------------- Read plain texts for permissions
                   10461: {
1.448     albertel 10462:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10463: 
                   10464:     while (my $configline=<$config>) {
1.448     albertel 10465: 	chomp($configline);
                   10466: 	if ($configline) {
1.742     raeburn  10467: 	    my ($short,@plain)=split(/:/,$configline);
                   10468:             %{$prp{$short}} = ();
                   10469: 	    if (@plain > 0) {
                   10470:                 $prp{$short}{'std'} = $plain[0];
                   10471:                 for (my $i=1; $i<@plain; $i++) {
                   10472:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10473:                 }
                   10474:             }
1.448     albertel 10475: 	}
1.135     www      10476:     }
1.448     albertel 10477:     close($config);
1.135     www      10478: }
                   10479: 
                   10480: # ---------------------------------------------------------- Read package table
                   10481: {
1.448     albertel 10482:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10483: 
                   10484:     while (my $configline=<$config>) {
1.483     albertel 10485: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10486: 	chomp($configline);
                   10487: 	my ($short,$plain)=split(/:/,$configline);
                   10488: 	my ($pack,$name)=split(/\&/,$short);
                   10489: 	if ($plain ne '') {
                   10490: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10491: 	    $packagetab{$short}=$plain; 
                   10492: 	}
1.11      www      10493:     }
1.448     albertel 10494:     close($config);
1.329     matthew  10495: }
                   10496: 
1.1073    raeburn  10497: # ---------------------------------------------------------- Read loncaparev table
                   10498: {
                   10499:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10500:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10501:             while (my $configline=<$config>) {
                   10502:                 chomp($configline);
                   10503:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10504:                 $loncaparevs{$hostid}=$loncaparev;
                   10505:             }
                   10506:             close($config);
                   10507:         }
                   10508:     }
                   10509: }
                   10510: 
1.1074    raeburn  10511: # ---------------------------------------------------------- Read serverhostID table
                   10512: {
                   10513:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10514:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10515:             while (my $configline=<$config>) {
                   10516:                 chomp($configline);
                   10517:                 my ($name,$id)=split(/:/,$configline);
                   10518:                 $serverhomeIDs{$name}=$id;
                   10519:             }
                   10520:             close($config);
                   10521:         }
                   10522:     }
                   10523: }
                   10524: 
1.1079    raeburn  10525: {
                   10526:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10527:     if (-e $file) {
                   10528:         my $parser = HTML::LCParser->new($file);
                   10529:         while (my $token = $parser->get_token()) {
                   10530:             if ($token->[0] eq 'S') {
                   10531:                 my $item = $token->[1];
                   10532:                 my $name = $token->[2]{'name'};
                   10533:                 my $value = $token->[2]{'value'};
                   10534:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10535:                     my $release = $parser->get_text();
                   10536:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10537:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10538:                 }
                   10539:             }
                   10540:         }
                   10541:     }
1.1073    raeburn  10542: }
                   10543: 
1.329     matthew  10544: # ------------- set up temporary directory
                   10545: {
                   10546:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10547: 
1.11      www      10548: }
                   10549: 
1.794     albertel 10550: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10551: 				'compress_threshold'=> 20_000,
                   10552:  			        });
1.185     www      10553: 
1.281     www      10554: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10555: $dumpcount=0;
1.958     www      10556: $locknum=0;
1.22      www      10557: 
1.163     harris41 10558: &logtouch();
1.672     albertel 10559: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10560: $readit=1;
1.564     albertel 10561:     {
                   10562: 	use integer;
                   10563: 	my $test=(2**32)+1;
1.568     albertel 10564: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10565: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10566:     }
1.195     www      10567: }
1.1       albertel 10568: }
1.179     www      10569: 
1.1       albertel 10570: 1;
1.191     harris41 10571: __END__
                   10572: 
1.243     albertel 10573: =pod
                   10574: 
1.191     harris41 10575: =head1 NAME
                   10576: 
1.243     albertel 10577: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10578: 
                   10579: =head1 SYNOPSIS
                   10580: 
1.243     albertel 10581: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10582: 
                   10583:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10584: 
1.243     albertel 10585: Common parameters:
                   10586: 
                   10587: =over 4
                   10588: 
                   10589: =item *
                   10590: 
                   10591: $uname : an internal username (if $cname expecting a course Id specifically)
                   10592: 
                   10593: =item *
                   10594: 
                   10595: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10596: 
                   10597: =item *
                   10598: 
                   10599: $symb : a resource instance identifier
                   10600: 
                   10601: =item *
                   10602: 
                   10603: $namespace : the name of a .db file that contains the data needed or
                   10604: being set.
                   10605: 
                   10606: =back
                   10607: 
1.394     bowersj2 10608: =head1 OVERVIEW
1.191     harris41 10609: 
1.394     bowersj2 10610: lonnet provides subroutines which interact with the
                   10611: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10612: about classes, users, and resources.
1.243     albertel 10613: 
                   10614: For many of these objects you can also use this to store data about
                   10615: them or modify them in various ways.
1.191     harris41 10616: 
1.394     bowersj2 10617: =head2 Symbs
1.191     harris41 10618: 
1.394     bowersj2 10619: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10620: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10621: map, the resource number of the resource in the map, and the URL of
                   10622: the resource itself. The latter is somewhat redundant, but might help
                   10623: if maps change.
                   10624: 
                   10625: An example is
                   10626: 
                   10627:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10628: 
                   10629: The respective map entry is
                   10630: 
                   10631:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10632:   title="Problem 2">
                   10633:  </resource>
                   10634: 
                   10635: Symbs are used by the random number generator, as well as to store and
                   10636: restore data specific to a certain instance of for example a problem.
                   10637: 
                   10638: =head2 Storing And Retrieving Data
                   10639: 
                   10640: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10641: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10642: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10643: is is the non-critical message twin of cstore. These functions are for
                   10644: handlers to store a perl hash to a user's permanent data space in an
                   10645: easy manner, and to retrieve it again on another call. It is expected
                   10646: that a handler would use this once at the beginning to retrieve data,
                   10647: and then again once at the end to send only the new data back.
                   10648: 
                   10649: The data is stored in the user's data directory on the user's
                   10650: homeserver under the ID of the course.
                   10651: 
                   10652: The hash that is returned by restore will have all of the previous
                   10653: value for all of the elements of the hash.
                   10654: 
                   10655: Example:
                   10656: 
                   10657:  #creating a hash
                   10658:  my %hash;
                   10659:  $hash{'foo'}='bar';
                   10660: 
                   10661:  #storing it
                   10662:  &Apache::lonnet::cstore(\%hash);
                   10663: 
                   10664:  #changing a value
                   10665:  $hash{'foo'}='notbar';
                   10666: 
                   10667:  #adding a new value
                   10668:  $hash{'bar'}='foo';
                   10669:  &Apache::lonnet::cstore(\%hash);
                   10670: 
                   10671:  #retrieving the hash
                   10672:  my %history=&Apache::lonnet::restore();
                   10673: 
                   10674:  #print the hash
                   10675:  foreach my $key (sort(keys(%history))) {
                   10676:    print("\%history{$key} = $history{$key}");
                   10677:  }
                   10678: 
                   10679: Will print out:
1.191     harris41 10680: 
1.394     bowersj2 10681:  %history{1:foo} = bar
                   10682:  %history{1:keys} = foo:timestamp
                   10683:  %history{1:timestamp} = 990455579
                   10684:  %history{2:bar} = foo
                   10685:  %history{2:foo} = notbar
                   10686:  %history{2:keys} = foo:bar:timestamp
                   10687:  %history{2:timestamp} = 990455580
                   10688:  %history{bar} = foo
                   10689:  %history{foo} = notbar
                   10690:  %history{timestamp} = 990455580
                   10691:  %history{version} = 2
                   10692: 
                   10693: Note that the special hash entries C<keys>, C<version> and
                   10694: C<timestamp> were added to the hash. C<version> will be equal to the
                   10695: total number of versions of the data that have been stored. The
                   10696: C<timestamp> attribute will be the UNIX time the hash was
                   10697: stored. C<keys> is available in every historical section to list which
                   10698: keys were added or changed at a specific historical revision of a
                   10699: hash.
                   10700: 
                   10701: B<Warning>: do not store the hash that restore returns directly. This
                   10702: will cause a mess since it will restore the historical keys as if the
                   10703: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10704: 
1.394     bowersj2 10705: Calling convention:
1.191     harris41 10706: 
1.394     bowersj2 10707:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10708:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10709: 
1.394     bowersj2 10710: For more detailed information, see lonnet specific documentation.
1.191     harris41 10711: 
1.394     bowersj2 10712: =head1 RETURN MESSAGES
1.191     harris41 10713: 
1.394     bowersj2 10714: =over 4
1.191     harris41 10715: 
1.394     bowersj2 10716: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10717: 
1.394     bowersj2 10718: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10719: when the connection is brought back up
1.191     harris41 10720: 
1.394     bowersj2 10721: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10722: for later delivery
1.191     harris41 10723: 
1.967     bisitz   10724: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10725: 
1.394     bowersj2 10726: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10727: that was requested
1.191     harris41 10728: 
1.243     albertel 10729: =back
1.191     harris41 10730: 
1.243     albertel 10731: =head1 PUBLIC SUBROUTINES
1.191     harris41 10732: 
1.243     albertel 10733: =head2 Session Environment Functions
1.191     harris41 10734: 
1.243     albertel 10735: =over 4
1.191     harris41 10736: 
1.394     bowersj2 10737: =item * 
                   10738: X<appenv()>
1.949     raeburn  10739: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10740: the user envirnoment file, and will be restored for each access this
1.620     albertel 10741: user makes during this session, also modifies the %env for the current
1.949     raeburn  10742: process. Optional rolesarrayref - if defined contains a reference to an array
                   10743: of roles which are exempt from the restriction on modifying user.role entries 
                   10744: in the user's environment.db and in %env.    
1.191     harris41 10745: 
                   10746: =item *
1.394     bowersj2 10747: X<delenv()>
1.987     raeburn  10748: B<delenv($delthis,$regexp)>: removes all items from the session
                   10749: environment file that begin with $delthis. If the 
                   10750: optional second arg - $regexp - is true, $delthis is treated as a 
                   10751: regular expression, otherwise \Q$delthis\E is used. 
                   10752: The values are also deleted from the current processes %env.
1.191     harris41 10753: 
1.795     albertel 10754: =item * get_env_multiple($name) 
                   10755: 
                   10756: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10757: values may be defined and end up as an array ref.
                   10758: 
                   10759: returns an array of values
                   10760: 
1.243     albertel 10761: =back
                   10762: 
                   10763: =head2 User Information
1.191     harris41 10764: 
1.243     albertel 10765: =over 4
1.191     harris41 10766: 
                   10767: =item *
1.394     bowersj2 10768: X<queryauthenticate()>
                   10769: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10770: authentication scheme
                   10771: 
                   10772: =item *
1.394     bowersj2 10773: X<authenticate()>
1.1073    raeburn  10774: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10775: authenticate user from domain's lib servers (first use the current
                   10776: one). C<$upass> should be the users password.
1.1073    raeburn  10777: $checkdefauth is optional (value is 1 if a check should be made to
                   10778:    authenticate user using default authentication method, and allow
                   10779:    account creation if username does not have account in the domain).
                   10780: $clientcancheckhost is optional (value is 1 if checking whether the
                   10781:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 10782: 
                   10783: =item *
1.394     bowersj2 10784: X<homeserver()>
                   10785: B<homeserver($uname,$udom)>: find the server which has
                   10786: the user's directory and files (there must be only one), this caches
                   10787: the answer, and also caches if there is a borken connection.
1.191     harris41 10788: 
                   10789: =item *
1.394     bowersj2 10790: X<idget()>
                   10791: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10792: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10793: username, and only 1 username per ID in a specific domain) (returns
                   10794: hash: id=>name,id=>name)
1.191     harris41 10795: 
                   10796: =item *
1.394     bowersj2 10797: X<idrget()>
                   10798: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10799: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10800: 
                   10801: =item *
1.394     bowersj2 10802: X<idput()>
                   10803: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10804: 
                   10805: =item *
1.394     bowersj2 10806: X<rolesinit()>
                   10807: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10808: 
                   10809: =item *
1.551     albertel 10810: X<getsection()>
                   10811: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10812: course $cname, return section name/number or '' for "not in course"
                   10813: and '-1' for "no section"
                   10814: 
                   10815: =item *
1.394     bowersj2 10816: X<userenvironment()>
                   10817: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10818: passed in @what from the requested user's environment, returns a hash
                   10819: 
1.858     raeburn  10820: =item * 
                   10821: X<userlog_query()>
1.859     albertel 10822: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10823: activity.log file. %filters defines filters applied when parsing the
                   10824: log file. These can be start or end timestamps, or the type of action
                   10825: - log to look for Login or Logout events, check for Checkin or
                   10826: Checkout, role for role selection. The response is in the form
                   10827: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10828: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10829: 
1.243     albertel 10830: =back
                   10831: 
                   10832: =head2 User Roles
                   10833: 
                   10834: =over 4
                   10835: 
                   10836: =item *
                   10837: 
1.810     raeburn  10838: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10839:  F: full access
                   10840:  U,I,K: authentication modes (cxx only)
                   10841:  '': forbidden
                   10842:  1: user needs to choose course
                   10843:  2: browse allowed
1.766     albertel 10844:  A: passphrase authentication needed
1.243     albertel 10845: 
                   10846: =item *
                   10847: 
                   10848: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10849: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10850: and course level
                   10851: 
                   10852: =item *
                   10853: 
1.988     raeburn  10854: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10855: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10856: $type is Course (default) or Community.
1.988     raeburn  10857: If $forcedefault evaluates to true, text returned will be default 
                   10858: text for $type. Otherwise, if this is a course, the text returned 
                   10859: will be a custom name for the role (if defined in the course's 
                   10860: environment).  If no custom name is defined the default is returned.
                   10861:    
1.832     raeburn  10862: =item *
                   10863: 
1.935     raeburn  10864: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10865: All arguments are optional. Returns a hash of a roles, either for
                   10866: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10867: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10868: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10869: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10870: For each key, value is set to colon-separated start and end times for
                   10871: the role.  If no username and domain are specified, will default to
1.934     raeburn  10872: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10873: of role statuses (active, future or previous), roles 
                   10874: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10875: to restrict the list of roles reported. If no array ref is 
                   10876: provided for types, will default to return only active roles.
1.834     albertel 10877: 
1.243     albertel 10878: =back
                   10879: 
                   10880: =head2 User Modification
                   10881: 
                   10882: =over 4
                   10883: 
                   10884: =item *
                   10885: 
1.957     raeburn  10886: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10887: user for the level given by URL.  Optional start and end dates (leave empty
                   10888: string or zero for "no date")
1.191     harris41 10889: 
                   10890: =item *
                   10891: 
1.243     albertel 10892: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10893: change a users, password, possible return values are: ok,
                   10894: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10895: refused
1.191     harris41 10896: 
                   10897: =item *
                   10898: 
1.243     albertel 10899: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10900: 
                   10901: =item *
                   10902: 
1.1058    raeburn  10903: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10904:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10905: 
                   10906: will update user information (firstname,middlename,lastname,generation,
                   10907: permanentemail), and if forceid is true, student/employee ID also.
                   10908: A user's institutional affiliation(s) can also be updated.
                   10909: User information fields will not be overwritten with empty entries 
                   10910: unless the field is included in the $candelete array reference.
                   10911: This array is included when a single user is modified via "Manage Users",
                   10912: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10913: 
                   10914: =item *
                   10915: 
1.286     matthew  10916: modifystudent
                   10917: 
1.957     raeburn  10918: modify a student's enrollment and identification information.
1.286     matthew  10919: The course id is resolved based on the current users environment.  
                   10920: This means the envoking user must be a course coordinator or otherwise
                   10921: associated with a course.
                   10922: 
1.297     matthew  10923: This call is essentially a wrapper for lonnet::modifyuser and
                   10924: lonnet::modify_student_enrollment
1.286     matthew  10925: 
                   10926: Inputs: 
                   10927: 
                   10928: =over 4
                   10929: 
1.957     raeburn  10930: =item B<$udom> Student's loncapa domain
1.286     matthew  10931: 
1.957     raeburn  10932: =item B<$uname> Student's loncapa login name
1.286     matthew  10933: 
1.964     bisitz   10934: =item B<$uid> Student/Employee ID
1.286     matthew  10935: 
1.957     raeburn  10936: =item B<$umode> Student's authentication mode
1.286     matthew  10937: 
1.957     raeburn  10938: =item B<$upass> Student's password
1.286     matthew  10939: 
1.957     raeburn  10940: =item B<$first> Student's first name
1.286     matthew  10941: 
1.957     raeburn  10942: =item B<$middle> Student's middle name
1.286     matthew  10943: 
1.957     raeburn  10944: =item B<$last> Student's last name
1.286     matthew  10945: 
1.957     raeburn  10946: =item B<$gene> Student's generation
1.286     matthew  10947: 
1.957     raeburn  10948: =item B<$usec> Student's section in course
1.286     matthew  10949: 
                   10950: =item B<$end> Unix time of the roles expiration
                   10951: 
                   10952: =item B<$start> Unix time of the roles start date
                   10953: 
                   10954: =item B<$forceid> If defined, allow $uid to be changed
                   10955: 
                   10956: =item B<$desiredhome> server to use as home server for student
                   10957: 
1.957     raeburn  10958: =item B<$email> Student's permanent e-mail address
                   10959: 
                   10960: =item B<$type> Type of enrollment (auto or manual)
                   10961: 
1.963     raeburn  10962: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10963: 
                   10964: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10965: 
1.963     raeburn  10966: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10967: 
1.963     raeburn  10968: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10969: 
1.963     raeburn  10970: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10971: 
1.286     matthew  10972: =back
1.297     matthew  10973: 
                   10974: =item *
                   10975: 
                   10976: modify_student_enrollment
                   10977: 
                   10978: Change a students enrollment status in a class.  The environment variable
                   10979: 'role.request.course' must be defined for this function to proceed.
                   10980: 
                   10981: Inputs:
                   10982: 
                   10983: =over 4
                   10984: 
                   10985: =item $udom, students domain
                   10986: 
                   10987: =item $uname, students name
                   10988: 
                   10989: =item $uid, students user id
                   10990: 
                   10991: =item $first, students first name
                   10992: 
                   10993: =item $middle
                   10994: 
                   10995: =item $last
                   10996: 
                   10997: =item $gene
                   10998: 
                   10999: =item $usec
                   11000: 
                   11001: =item $end
                   11002: 
                   11003: =item $start
                   11004: 
1.957     raeburn  11005: =item $type
                   11006: 
                   11007: =item $locktype
                   11008: 
                   11009: =item $cid
                   11010: 
                   11011: =item $selfenroll
                   11012: 
                   11013: =item $context
                   11014: 
1.297     matthew  11015: =back
                   11016: 
1.191     harris41 11017: 
                   11018: =item *
                   11019: 
1.243     albertel 11020: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11021: custom role; give a custom role to a user for the level given by URL.  Specify
                   11022: name and domain of role author, and role name
1.191     harris41 11023: 
                   11024: =item *
                   11025: 
1.243     albertel 11026: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11027: 
                   11028: =item *
                   11029: 
1.243     albertel 11030: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11031: 
                   11032: =back
                   11033: 
                   11034: =head2 Course Infomation
                   11035: 
                   11036: =over 4
1.191     harris41 11037: 
                   11038: =item *
                   11039: 
1.631     albertel 11040: coursedescription($courseid) : returns a hash of information about the
                   11041: specified course id, including all environment settings for the
                   11042: course, the description of the course will be in the hash under the
                   11043: key 'description'
1.191     harris41 11044: 
                   11045: =item *
                   11046: 
1.624     albertel 11047: resdata($name,$domain,$type,@which) : request for current parameter
                   11048: setting for a specific $type, where $type is either 'course' or 'user',
                   11049: @what should be a list of parameters to ask about. This routine caches
                   11050: answers for 5 minutes.
1.243     albertel 11051: 
1.877     foxr     11052: =item *
                   11053: 
                   11054: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11055: data base, returning a hash that is keyed by the resource name and has
                   11056: values that are the resource value.  I believe that the timestamps and
                   11057: versions are also returned.
                   11058: 
                   11059: 
1.243     albertel 11060: =back
                   11061: 
                   11062: =head2 Course Modification
                   11063: 
                   11064: =over 4
1.191     harris41 11065: 
                   11066: =item *
                   11067: 
1.243     albertel 11068: writecoursepref($courseid,%prefs) : write preferences (environment
                   11069: database) for a course
1.191     harris41 11070: 
                   11071: =item *
                   11072: 
1.1011    raeburn  11073: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11074: 
                   11075: =item *
                   11076: 
1.1038    raeburn  11077: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11078: 
                   11079: =back
                   11080: 
                   11081: =head2 Resource Subroutines
                   11082: 
                   11083: =over 4
1.191     harris41 11084: 
                   11085: =item *
                   11086: 
1.243     albertel 11087: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11088: 
                   11089: =item *
                   11090: 
1.243     albertel 11091: repcopy($filename) : subscribes to the requested file, and attempts to
                   11092: replicate from the owning library server, Might return
1.607     raeburn  11093: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11094: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11095: resource. Expects the local filesystem pathname
                   11096: (/home/httpd/html/res/....)
                   11097: 
                   11098: =back
                   11099: 
                   11100: =head2 Resource Information
                   11101: 
                   11102: =over 4
1.191     harris41 11103: 
                   11104: =item *
                   11105: 
1.243     albertel 11106: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11107: a vairety of different possible values, $varname should be a request
                   11108: string, and the other parameters can be used to specify who and what
                   11109: one is asking about.
                   11110: 
                   11111: Possible values for $varname are environment.lastname (or other item
                   11112: from the envirnment hash), user.name (or someother aspect about the
                   11113: user), resource.0.maxtries (or some other part and parameter of a
                   11114: resource)
1.204     albertel 11115: 
                   11116: =item *
                   11117: 
1.243     albertel 11118: directcondval($number) : get current value of a condition; reads from a state
                   11119: string
1.204     albertel 11120: 
                   11121: =item *
                   11122: 
1.243     albertel 11123: condval($condidx) : value of condition index based on state
1.204     albertel 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11128: resource's metadata, $what should be either a specific key, or either
                   11129: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11130: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11131: 
                   11132: this function automatically caches all requests
1.191     harris41 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11137: network of library servers; returns file handle of where SQL and regex results
                   11138: will be stored for query
1.191     harris41 11139: 
                   11140: =item *
                   11141: 
1.243     albertel 11142: symbread($filename) : return symbolic list entry (filename argument optional);
                   11143: returns the data handle
1.191     harris41 11144: 
                   11145: =item *
                   11146: 
1.243     albertel 11147: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11148: a possible symb for the URL in $thisfn, and if is an encryypted
                   11149: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11150: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11151: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11152: 
1.191     harris41 11153: 
                   11154: =item *
                   11155: 
1.243     albertel 11156: symbclean($symb) : removes versions numbers from a symb, returns the
                   11157: cleaned symb
1.191     harris41 11158: 
                   11159: =item *
                   11160: 
1.243     albertel 11161: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11162: course map, user must be in a course for it to work.
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.243     albertel 11166: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11167: 
                   11168: =item *
                   11169: 
1.243     albertel 11170: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11171: a random seed, all arguments are optional, if they aren't sent it uses the
                   11172: environment to derive them. Note: if symb isn't sent and it can't get one
                   11173: from &symbread it will use the current time as its return value
1.191     harris41 11174: 
                   11175: =item *
                   11176: 
1.243     albertel 11177: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11178: unfakeable, receipt
1.191     harris41 11179: 
                   11180: =item *
                   11181: 
1.620     albertel 11182: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11183: 
                   11184: =item *
                   11185: 
1.243     albertel 11186: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11187: 
                   11188: =item *
                   11189: 
1.243     albertel 11190: 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 11191: 
                   11192: =item *
                   11193: 
1.243     albertel 11194: 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 11195: 
                   11196: =item *
                   11197: 
1.243     albertel 11198: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.243     albertel 11202: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11203: forcing spreadsheet to reevaluate the resource scores next time.
                   11204: 
                   11205: =back
                   11206: 
                   11207: =head2 Storing/Retreiving Data
                   11208: 
                   11209: =over 4
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
1.243     albertel 11213: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11214: for this url; hashref needs to be given and should be a \%hashname; the
                   11215: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11216: be derived from the env
1.191     harris41 11217: 
                   11218: =item *
                   11219: 
1.243     albertel 11220: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11221: uses critical subroutine
1.191     harris41 11222: 
                   11223: =item *
                   11224: 
1.243     albertel 11225: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11226: all args are optional
1.191     harris41 11227: 
                   11228: =item *
                   11229: 
1.717     albertel 11230: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11231: dumps the complete (or key matching regexp) namespace into a hash
                   11232: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11233: normally &store()ed into
                   11234: 
                   11235: $range should be either an integer '100' (give me the first 100
                   11236:                                            matching records)
                   11237:               or be  two integers sperated by a - with no spaces
                   11238:                  '30-50' (give me the 30th through the 50th matching
                   11239:                           records)
                   11240: 
                   11241: 
                   11242: =item *
                   11243: 
                   11244: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11245: replaces a &store() version of data with a replacement set of data
                   11246: for a particular resource in a namespace passed in the $storehash hash 
                   11247: reference
                   11248: 
                   11249: =item *
                   11250: 
1.243     albertel 11251: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11252: works very similar to store/cstore, but all data is stored in a
                   11253: temporary location and can be reset using tmpreset, $storehash should
                   11254: be a hash reference, returns nothing on success
1.191     harris41 11255: 
                   11256: =item *
                   11257: 
1.243     albertel 11258: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11259: similar to restore, but all data is stored in a temporary location and
                   11260: can be reset using tmpreset. Returns a hash of values on success,
                   11261: error string otherwise.
1.191     harris41 11262: 
                   11263: =item *
                   11264: 
1.243     albertel 11265: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11266: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11267: 
                   11268: =item *
                   11269: 
1.243     albertel 11270: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11271: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11272: 
                   11273: =item *
                   11274: 
1.243     albertel 11275: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11276: namesp ($udom and $uname are optional)
1.191     harris41 11277: 
                   11278: =item *
                   11279: 
1.702     albertel 11280: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11281: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11282: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11283: 
1.702     albertel 11284: $range should be either an integer '100' (give me the first 100
                   11285:                                            matching records)
                   11286:               or be  two integers sperated by a - with no spaces
                   11287:                  '30-50' (give me the 30th through the 50th matching
                   11288:                           records)
1.449     matthew  11289: =item *
                   11290: 
                   11291: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11292: $store can be a scalar, an array reference, or if the amount to be 
                   11293: incremented is > 1, a hash reference.
                   11294: 
                   11295: ($udom and $uname are optional)
1.191     harris41 11296: 
                   11297: =item *
                   11298: 
1.243     albertel 11299: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11300: ($udom and $uname are optional)
1.191     harris41 11301: 
                   11302: =item *
                   11303: 
1.243     albertel 11304: cput($namespace,$storehash,$udom,$uname) : critical put
                   11305: ($udom and $uname are optional)
1.191     harris41 11306: 
                   11307: =item *
                   11308: 
1.748     albertel 11309: newput($namespace,$storehash,$udom,$uname) :
                   11310: 
                   11311: Attempts to store the items in the $storehash, but only if they don't
                   11312: currently exist, if this succeeds you can be certain that you have 
                   11313: successfully created a new key value pair in the $namespace db.
                   11314: 
                   11315: 
                   11316: Args:
                   11317:  $namespace: name of database to store values to
                   11318:  $storehash: hashref to store to the db
                   11319:  $udom: (optional) domain of user containing the db
                   11320:  $uname: (optional) name of user caontaining the db
                   11321: 
                   11322: Returns:
                   11323:  'ok' -> succeeded in storing all keys of $storehash
                   11324:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11325:                         least <key> already existed in the db (other
                   11326:                         requested keys may also already exist)
1.967     bisitz   11327:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11328:  'con_lost' -> unable to contact request server
                   11329:  'refused' -> action was not allowed by remote machine
                   11330: 
                   11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11335: reference filled in from namesp (encrypts the return communication)
                   11336: ($udom and $uname are optional)
1.191     harris41 11337: 
                   11338: =item *
                   11339: 
1.243     albertel 11340: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11341: critical subroutine
                   11342: 
1.806     raeburn  11343: =item *
                   11344: 
1.860     raeburn  11345: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11346: array reference filled in from namespace found in domain level on either
                   11347: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11348: 
                   11349: =item *
                   11350: 
1.860     raeburn  11351: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11352: domain level either on specified domain server ($uhome) or primary domain 
                   11353: server ($udom and $uhome are optional)
1.806     raeburn  11354: 
1.943     raeburn  11355: =item * 
                   11356: 
                   11357: get_domain_defaults($target_domain) : returns hash with defaults for
                   11358: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11359: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11360: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11361: Values are retrieved from cache (if current), or from domain's configuration.db
                   11362: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11363: or lonTabs/domain.tab. 
                   11364: 
                   11365: %domdefaults = &get_auth_defaults($target_domain);
                   11366: 
1.243     albertel 11367: =back
                   11368: 
                   11369: =head2 Network Status Functions
                   11370: 
                   11371: =over 4
1.191     harris41 11372: 
                   11373: =item *
                   11374: 
                   11375: dirlist($uri) : return directory list based on URI
                   11376: 
                   11377: =item *
                   11378: 
1.243     albertel 11379: spareserver() : find server with least workload from spare.tab
                   11380: 
1.986     foxr     11381: 
                   11382: =item *
                   11383: 
                   11384: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11385: if there is no corresponding loncapa host.
                   11386: 
1.243     albertel 11387: =back
                   11388: 
1.986     foxr     11389: 
1.243     albertel 11390: =head2 Apache Request
                   11391: 
                   11392: =over 4
1.191     harris41 11393: 
                   11394: =item *
                   11395: 
1.243     albertel 11396: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11397: localhost, posts hash
                   11398: 
                   11399: =back
                   11400: 
                   11401: =head2 Data to String to Data
                   11402: 
                   11403: =over 4
1.191     harris41 11404: 
                   11405: =item *
                   11406: 
1.243     albertel 11407: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11408: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11409: 
                   11410: =item *
                   11411: 
1.243     albertel 11412: hashref2str($hashref) : convert a hashref into a string complete with
                   11413: escaping and '=' and '&' separators, supports elements that are
                   11414: arrayrefs and hashrefs
1.191     harris41 11415: 
                   11416: =item *
                   11417: 
1.243     albertel 11418: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11419: with escaping and '&' separators, supports elements that are arrayrefs
                   11420: and hashrefs
1.191     harris41 11421: 
                   11422: =item *
                   11423: 
1.243     albertel 11424: str2hash($string) : convert string to hash using unescaping and
                   11425: splitting on '=' and '&', supports elements that are arrayrefs and
                   11426: hashrefs
1.191     harris41 11427: 
                   11428: =item *
                   11429: 
1.243     albertel 11430: str2array($string) : convert string to hash using unescaping and
                   11431: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11432: 
                   11433: =back
                   11434: 
                   11435: =head2 Logging Routines
                   11436: 
                   11437: =over 4
                   11438: 
                   11439: These routines allow one to make log messages in the lonnet.log and
                   11440: lonnet.perm logfiles.
1.191     harris41 11441: 
                   11442: =item *
                   11443: 
1.243     albertel 11444: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11445: 
                   11446: =item *
                   11447: 
1.243     albertel 11448: logthis() : append message to the normal lonnet.log file, it gets
                   11449: preiodically rolled over and deleted.
1.191     harris41 11450: 
                   11451: =item *
                   11452: 
1.243     albertel 11453: logperm() : append a permanent message to lonnet.perm.log, this log
                   11454: file never gets deleted by any automated portion of the system, only
                   11455: messages of critical importance should go in here.
                   11456: 
                   11457: =back
                   11458: 
                   11459: =head2 General File Helper Routines
                   11460: 
                   11461: =over 4
1.191     harris41 11462: 
                   11463: =item *
                   11464: 
1.481     raeburn  11465: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11466: (a) files in /uploaded
                   11467:   (i) If a local copy of the file exists - 
                   11468:       compares modification date of local copy with last-modified date for 
                   11469:       definitive version stored on home server for course. If local copy is 
                   11470:       stale, requests a new version from the home server and stores it. 
                   11471:       If the original has been removed from the home server, then local copy 
                   11472:       is unlinked.
                   11473:   (ii) If local copy does not exist -
                   11474:       requests the file from the home server and stores it. 
                   11475:   
                   11476:   If $caller is 'uploadrep':  
                   11477:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11478:     for request for files originally uploaded via DOCS. 
                   11479:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11480:   
                   11481:   Otherwise:
                   11482:      This indicates a call from the content generation phase of the request.
                   11483:      -  returns the entire contents of the file or -1.
                   11484:      
                   11485: (b) files in /res
                   11486:    - returns the entire contents of a file or -1; 
                   11487:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11488: 
1.712     albertel 11489: 
                   11490: =item *
                   11491: 
                   11492: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11493:                   reference
                   11494: 
                   11495: returns either a stat() list of data about the file or an empty list
                   11496: if the file doesn't exist or couldn't find out about it (connection
                   11497: problems or user unknown)
                   11498: 
1.191     harris41 11499: =item *
                   11500: 
1.243     albertel 11501: filelocation($dir,$file) : returns file system location of a file
                   11502: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11503: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11504: and a file of ../bob will become /a/bob)
1.191     harris41 11505: 
                   11506: =item *
                   11507: 
                   11508: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11509: filelocation except for hrefs
                   11510: 
                   11511: =item *
                   11512: 
                   11513: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11514: 
1.243     albertel 11515: =back
                   11516: 
1.608     albertel 11517: =head2 Usererfile file routines (/uploaded*)
                   11518: 
                   11519: =over 4
                   11520: 
                   11521: =item *
                   11522: 
                   11523: userfileupload(): main rotine for putting a file in a user or course's
                   11524:                   filespace, arguments are,
                   11525: 
1.620     albertel 11526:  formname - required - this is the name of the element in $env where the
1.608     albertel 11527:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11528:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11529:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11530:  context - if coursedoc, store the file in the course of the active role
                   11531:              of the current user; 
                   11532:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11533:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11534:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11535:          if undefined, it will be placed in "unknown"
                   11536: 
                   11537:  (This routine calls clean_filename() to remove any dangerous
                   11538:  characters from the filename, and then calls finuserfileupload() to
                   11539:  complete the transaction)
                   11540: 
                   11541:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11542:  and /adm/notfound.html if unsuccessful
                   11543: 
                   11544: =item *
                   11545: 
                   11546: clean_filename(): routine for cleaing a filename up for storage in
                   11547:                  userfile space, argument is:
                   11548: 
                   11549:  filename - proposed filename
                   11550: 
                   11551: returns: the new clean filename
                   11552: 
                   11553: =item *
                   11554: 
1.1090    raeburn  11555: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11556: userspace, probably shouldn't be called directly
                   11557: 
                   11558:   docuname: username or courseid of destination for the file
                   11559:   docudom: domain of user/course of destination for the file
                   11560:   formname: same as for userfileupload()
1.1090    raeburn  11561:   fname: filename (including subdirectories) for the file
                   11562:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11563:   allfiles: reference to hash used to store objects found by parser
                   11564:   codebase: reference to hash used for codebases of java objects found by parser
                   11565:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11566:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11567:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11568:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11569:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11570:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11571:   mimetype: reference to scalar to accommodate mime type determined
                   11572:             from File::MMagic if $parser = parse.
1.608     albertel 11573: 
                   11574:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11575:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11576:  was 'overwrite').
                   11577:  
1.608     albertel 11578: 
                   11579: =item *
                   11580: 
                   11581: renameuserfile(): renames an existing userfile to a new name
                   11582: 
                   11583:   Args:
                   11584:    docuname: username or courseid of destination for the file
                   11585:    docudom: domain of user/course of destination for the file
                   11586:    old: current file name (including any subdirs under userfiles)
                   11587:    new: desired file name (including any subdirs under userfiles)
                   11588: 
                   11589: =item *
                   11590: 
                   11591: mkdiruserfile(): creates a directory is a userfiles dir
                   11592: 
                   11593:   Args:
                   11594:    docuname: username or courseid of destination for the file
                   11595:    docudom: domain of user/course of destination for the file
                   11596:    dir: dir to create (including any subdirs under userfiles)
                   11597: 
                   11598: =item *
                   11599: 
                   11600: removeuserfile(): removes a file that exists in userfiles
                   11601: 
                   11602:   Args:
                   11603:    docuname: username or courseid of destination for the file
                   11604:    docudom: domain of user/course of destination for the file
                   11605:    fname: filname to delete (including any subdirs under userfiles)
                   11606: 
                   11607: =item *
                   11608: 
                   11609: removeuploadedurl(): convience function for removeuserfile()
                   11610: 
                   11611:   Args:
                   11612:    url:  a full /uploaded/... url to delete
                   11613: 
1.747     albertel 11614: =item * 
                   11615: 
                   11616: get_portfile_permissions():
                   11617:   Args:
                   11618:     domain: domain of user or course contain the portfolio files
                   11619:     user: name of user or num of course contain the portfolio files
                   11620:   Returns:
                   11621:     hashref of a dump of the proper file_permissions.db
                   11622:    
                   11623: 
                   11624: =item * 
                   11625: 
                   11626: get_access_controls():
                   11627: 
                   11628: Args:
                   11629:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11630:   group: (optional) the group you want the files associated with
                   11631:   file: (optional) the file you want access info on
                   11632: 
                   11633: Returns:
1.749     raeburn  11634:     a hash (keys are file names) of hashes containing
                   11635:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11636:         values are XML containing access control settings (see below) 
1.747     albertel 11637: 
                   11638: Internal notes:
                   11639: 
1.749     raeburn  11640:  access controls are stored in file_permissions.db as key=value pairs.
                   11641:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11642:         where scope -> public,guest,course,group,domains or users.
                   11643:               end -> UNIX time for end of access (0 -> no end date)
                   11644:               start -> UNIX time for start of access
                   11645: 
                   11646:     value -> XML description of access control
                   11647:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11648:             <start></start>
                   11649:             <end></end>
                   11650: 
                   11651:             <password></password>  for scope type = guest
                   11652: 
                   11653:             <domain></domain>     for scope type = course or group
                   11654:             <number></number>
                   11655:             <roles id="">
                   11656:              <role></role>
                   11657:              <access></access>
                   11658:              <section></section>
                   11659:              <group></group>
                   11660:             </roles>
                   11661: 
                   11662:             <dom></dom>         for scope type = domains
                   11663: 
                   11664:             <users>             for scope type = users
                   11665:              <user>
                   11666:               <uname></uname>
                   11667:               <udom></udom>
                   11668:              </user>
                   11669:             </users>
                   11670:            </scope> 
                   11671:               
                   11672:  Access data is also aggregated for each file in an additional key=value pair:
                   11673:  key -> path to file/file_name\0accesscontrol 
                   11674:  value -> reference to hash
                   11675:           hash contains key = value pairs
                   11676:           where key = uniqueID:scope_end_start
                   11677:                 value = UNIX time record was last updated
                   11678: 
                   11679:           Used to improve speed of look-ups of access controls for each file.  
                   11680:  
                   11681:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11682: 
                   11683: modify_access_controls():
                   11684: 
                   11685: Modifies access controls for a portfolio file
                   11686: Args
                   11687: 1. file name
                   11688: 2. reference to hash of required changes,
                   11689: 3. domain
                   11690: 4. username
                   11691:   where domain,username are the domain of the portfolio owner 
                   11692:   (either a user or a course) 
                   11693: 
                   11694: Returns:
                   11695: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11696: 2. result of deletions ('ok' or 'error', with error message).
                   11697: 3. reference to hash of any new or updated access controls.
                   11698: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11699:    key = integer (inbound ID)
                   11700:    value = uniqueID  
1.747     albertel 11701: 
1.608     albertel 11702: =back
                   11703: 
1.243     albertel 11704: =head2 HTTP Helper Routines
                   11705: 
                   11706: =over 4
                   11707: 
1.191     harris41 11708: =item *
                   11709: 
                   11710: escape() : unpack non-word characters into CGI-compatible hex codes
                   11711: 
                   11712: =item *
                   11713: 
                   11714: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11715: 
1.243     albertel 11716: =back
                   11717: 
                   11718: =head1 PRIVATE SUBROUTINES
                   11719: 
                   11720: =head2 Underlying communication routines (Shouldn't call)
                   11721: 
                   11722: =over 4
                   11723: 
                   11724: =item *
                   11725: 
                   11726: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11727: 
                   11728: =item *
                   11729: 
                   11730: reply() : uses subreply to send a message to remote machine, logs all failures
                   11731: 
                   11732: =item *
                   11733: 
                   11734: critical() : passes a critical message to another server; if cannot
                   11735: get through then place message in connection buffer directory and
                   11736: returns con_delayed, if incapable of saving message, returns
                   11737: con_failed
                   11738: 
                   11739: =item *
                   11740: 
                   11741: reconlonc() : tries to reconnect lonc client processes.
                   11742: 
                   11743: =back
                   11744: 
                   11745: =head2 Resource Access Logging
                   11746: 
                   11747: =over 4
                   11748: 
                   11749: =item *
                   11750: 
                   11751: flushcourselogs() : flush (save) buffer logs and access logs
                   11752: 
                   11753: =item *
                   11754: 
                   11755: courselog($what) : save message for course in hash
                   11756: 
                   11757: =item *
                   11758: 
                   11759: courseacclog($what) : save message for course using &courselog().  Perform
                   11760: special processing for specific resource types (problems, exams, quizzes, etc).
                   11761: 
1.191     harris41 11762: =item *
                   11763: 
                   11764: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11765: as a PerlChildExitHandler
1.243     albertel 11766: 
                   11767: =back
                   11768: 
                   11769: =head2 Other
                   11770: 
                   11771: =over 4
                   11772: 
                   11773: =item *
                   11774: 
                   11775: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11776: 
                   11777: =back
                   11778: 
                   11779: =cut
1.877     foxr     11780: 

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