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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.14! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.13 2010/11/09 20:55:34 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.5  raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1056.4.13  raeburn    98: use File::Copy;
1.676     albertel   99: 
1.195     www       100: my $readit;
1.550     foxr      101: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  102: 
1.619     albertel  103: require Exporter;
                    104: 
                    105: our @ISA = qw (Exporter);
                    106: our @EXPORT = qw(%env);
                    107: 
1.449     matthew   108: 
1.1       albertel  109: # --------------------------------------------------------------------- Logging
1.729     www       110: {
                    111:     my $logid;
                    112:     sub instructor_log {
1.957     raeburn   113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    114:         if (($cnum eq '') || ($cdom eq '')) {
                    115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    117:         }
1.729     www       118: 	$logid++;
1.957     raeburn   119:         my $now = time();
                    120: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       122: 				    { $id => {
                    123: 					'exe_uname' => $env{'user.name'},
                    124: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   125: 					'exe_time'  => $now,
1.730     www       126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    127: 					'delflag'   => $delflag,
                    128: 					'logentry'  => $storehash,
                    129: 					'uname'     => $uname,
                    130: 					'udom'      => $udom,
                    131: 				    }
1.957     raeburn   132: 				  },$cdom,$cnum);
1.729     www       133:     }
                    134: }
1.1       albertel  135: 
1.163     harris41  136: sub logtouch {
                    137:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  138:     unless (-e "$execdir/logs/lonnet.log") {	
                    139: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  140: 	close $fh;
                    141:     }
                    142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    144: }
                    145: 
1.1       albertel  146: sub logthis {
                    147:     my $message=shift;
                    148:     my $execdir=$perlvar{'lonDaemons'};
                    149:     my $now=time;
                    150:     my $local=localtime($now);
1.448     albertel  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    153: 	print $fh $logstring;
1.448     albertel  154: 	close($fh);
                    155:     }
1.1       albertel  156:     return 1;
                    157: }
                    158: 
                    159: sub logperm {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.448     albertel  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    165: 	print $fh "$now:$message:$local\n";
                    166: 	close($fh);
                    167:     }
1.1       albertel  168:     return 1;
                    169: }
                    170: 
1.850     albertel  171: sub create_connection {
1.853     albertel  172:     my ($hostname,$lonid) = @_;
1.851     albertel  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  174: 				     Type    => SOCK_STREAM,
                    175: 				     Timeout => 10);
                    176:     return 0 if (!$client);
1.890     albertel  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  178:     my $result = <$client>;
                    179:     chomp($result);
                    180:     return 1 if ($result eq 'done');
                    181:     return 0;
                    182: }
                    183: 
1.983     raeburn   184: sub get_server_timezone {
                    185:     my ($cnum,$cdom) = @_;
                    186:     my $home=&homeserver($cnum,$cdom);
                    187:     if ($home ne 'no_host') {
                    188:         my $cachetime = 24*3600;
                    189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    190:         if (defined($cached)) {
                    191:             return $timezone;
                    192:         } else {
                    193:             my $timezone = &reply('servertimezone',$home);
                    194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    195:         }
                    196:     }
                    197: }
1.850     albertel  198: 
1.993     raeburn   199: sub get_server_loncaparev {
1.1056.4.3  raeburn   200:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   201:     if (defined($lonhost)) {
                    202:         if (!defined(&hostname($lonhost))) {
                    203:             undef($lonhost);
                    204:         }
                    205:     }
                    206:     if (!defined($lonhost)) {
                    207:         if (defined(&domain($dom,'primary'))) {
                    208:             $lonhost=&domain($dom,'primary');
                    209:             if ($lonhost eq 'no_host') {
                    210:                 undef($lonhost);
                    211:             }
                    212:         }
                    213:     }
                    214:     if (defined($lonhost)) {
1.1056.4.3  raeburn   215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $loncaparev;
                    220:             }
                    221:         }
                    222:         my ($answer,$loncaparev);
                    223:         my @ids=&current_machine_ids();
                    224:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    225:             $answer = $perlvar{'lonVersion'};
1.1056.4.7  raeburn   226:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   227:                 $loncaparev = $1;
                    228:             }
                    229:         } else {
                    230:             $answer = &reply('serverloncaparev',$lonhost);
                    231:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    232:                 if ($caller eq 'loncron') {
                    233:                     my $ua=new LWP::UserAgent;
1.1056.4.8  raeburn   234:                     $ua->timeout(4);
1.1056.4.3  raeburn   235:                     my $protocol = $protocol{$lonhost};
                    236:                     $protocol = 'http' if ($protocol ne 'https');
                    237:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    238:                     my $request=new HTTP::Request('GET',$url);
                    239:                     my $response=$ua->request($request);
                    240:                     unless ($response->is_error()) {
                    241:                         my $content = $response->content;
1.1056.4.7  raeburn   242:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   243:                             $loncaparev = $1;
                    244:                         }
                    245:                     }
                    246:                 } else {
                    247:                     $loncaparev = $loncaparevs{$lonhost};
                    248:                 }
1.1056.4.7  raeburn   249:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   250:                 $loncaparev = $1;
                    251:             }
                    252:         }
                    253:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    254:     }
                    255: }
                    256: 
                    257: sub get_server_homeID {
                    258:     my ($hostname,$ignore_cache,$caller) = @_;
                    259:     unless ($ignore_cache) {
                    260:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   261:         if (defined($cached)) {
1.1056.4.3  raeburn   262:             return $serverhomeID;
                    263:         }
                    264:     }
                    265:     my $cachetime = 12*3600;
                    266:     my $serverhomeID;
                    267:     if ($caller eq 'loncron') {
                    268:         my @machine_ids = &machine_ids($hostname);
                    269:         foreach my $id (@machine_ids) {
                    270:             my $response = &reply('serverhomeID',$id);
                    271:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    272:                 $serverhomeID = $response;
                    273:                 last;
                    274:             }
1.993     raeburn   275:         }
1.1056.4.3  raeburn   276:         if ($serverhomeID eq '') {
                    277:             $serverhomeID = $machine_ids[-1];
                    278:         }
                    279:     } else {
                    280:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   281:     }
1.1056.4.3  raeburn   282:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   283: }
                    284: 
1.1       albertel  285: # -------------------------------------------------- Non-critical communication
                    286: sub subreply {
                    287:     my ($cmd,$server)=@_;
1.838     albertel  288:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      289:     #
                    290:     #  With loncnew process trimming, there's a timing hole between lonc server
                    291:     #  process exit and the master server picking up the listen on the AF_UNIX
                    292:     #  socket.  In that time interval, a lock file will exist:
                    293: 
                    294:     my $lockfile=$peerfile.".lock";
                    295:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    296: 	sleep(1);
                    297:     }
                    298:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      299:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      300:     #
1.550     foxr      301:     #   We'll give the connection a few tries before abandoning it.  If
                    302:     #   connection is not possible, we'll con_lost back to the client.
                    303:     #   
                    304:     my $client;
                    305:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    306: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    307: 				      Type    => SOCK_STREAM,
                    308: 				      Timeout => 10);
1.869     albertel  309: 	if ($client) {
1.550     foxr      310: 	    last;		# Connected!
1.850     albertel  311: 	} else {
1.853     albertel  312: 	    &create_connection(&hostname($server),$server);
1.550     foxr      313: 	}
1.850     albertel  314:         sleep(1);		# Try again later if failed connection.
1.550     foxr      315:     }
                    316:     my $answer;
                    317:     if ($client) {
1.704     albertel  318: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      319: 	$answer=<$client>;
                    320: 	if (!$answer) { $answer="con_lost"; }
                    321: 	chomp($answer);
                    322:     } else {
                    323: 	$answer = 'con_lost';	# Failed connection.
                    324:     }
1.1       albertel  325:     return $answer;
                    326: }
                    327: 
                    328: sub reply {
                    329:     my ($cmd,$server)=@_;
1.838     albertel  330:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  331:     my $answer=subreply($cmd,$server);
1.65      www       332:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  333:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       334:                 " $cmd to $server returned $answer</font>");
                    335:     }
1.1       albertel  336:     return $answer;
                    337: }
                    338: 
                    339: # ----------------------------------------------------------- Send USR1 to lonc
                    340: 
                    341: sub reconlonc {
1.891     albertel  342:     my ($lonid) = @_;
                    343:     my $hostname = &hostname($lonid);
                    344:     if ($lonid) {
                    345: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    346: 	if ($hostname && -e $peerfile) {
                    347: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    348: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    349: 					     Type    => SOCK_STREAM,
                    350: 					     Timeout => 10);
                    351: 	    if ($client) {
                    352: 		print $client ("reset_retries\n");
                    353: 		my $answer=<$client>;
                    354: 		#reset just this one.
                    355: 	    }
                    356: 	}
                    357: 	return;
                    358:     }
                    359: 
1.836     www       360:     &logthis("Trying to reconnect lonc");
1.1       albertel  361:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  362:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  363: 	my $loncpid=<$fh>;
                    364:         chomp($loncpid);
                    365:         if (kill 0 => $loncpid) {
                    366: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    367:             kill USR1 => $loncpid;
                    368:             sleep 1;
1.836     www       369:          } else {
1.12      www       370: 	    &logthis(
1.672     albertel  371:                "<font color=\"blue\">WARNING:".
1.12      www       372:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  373:         }
                    374:     } else {
1.836     www       375: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  376:     }
                    377: }
                    378: 
                    379: # ------------------------------------------------------ Critical communication
1.12      www       380: 
1.1       albertel  381: sub critical {
                    382:     my ($cmd,$server)=@_;
1.838     albertel  383:     unless (&hostname($server)) {
1.672     albertel  384:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       385:                " Critical message to unknown server ($server)</font>");
                    386:         return 'no_such_host';
                    387:     }
1.1       albertel  388:     my $answer=reply($cmd,$server);
                    389:     if ($answer eq 'con_lost') {
                    390: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  391: 	my $answer=reply($cmd,$server);
1.1       albertel  392:         if ($answer eq 'con_lost') {
                    393:             my $now=time;
                    394:             my $middlename=$cmd;
1.5       www       395:             $middlename=substr($middlename,0,16);
1.1       albertel  396:             $middlename=~s/\W//g;
                    397:             my $dfilename=
1.305     www       398:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    399:             $dumpcount++;
1.1       albertel  400:             {
1.448     albertel  401: 		my $dfh;
                    402: 		if (open($dfh,">$dfilename")) {
                    403: 		    print $dfh "$cmd\n"; 
                    404: 		    close($dfh);
                    405: 		}
1.1       albertel  406:             }
                    407:             sleep 2;
                    408:             my $wcmd='';
                    409:             {
1.448     albertel  410: 		my $dfh;
                    411: 		if (open($dfh,"<$dfilename")) {
                    412: 		    $wcmd=<$dfh>; 
                    413: 		    close($dfh);
                    414: 		}
1.1       albertel  415:             }
                    416:             chomp($wcmd);
1.7       www       417:             if ($wcmd eq $cmd) {
1.672     albertel  418: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       419:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  420:                 &logperm("D:$server:$cmd");
                    421: 	        return 'con_delayed';
                    422:             } else {
1.672     albertel  423:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       424:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  425:                 &logperm("F:$server:$cmd");
                    426:                 return 'con_failed';
                    427:             }
                    428:         }
                    429:     }
                    430:     return $answer;
1.405     albertel  431: }
                    432: 
1.755     albertel  433: # ------------------------------------------- check if return value is an error
                    434: 
                    435: sub error {
                    436:     my ($result) = @_;
1.756     albertel  437:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  438: 	if ($2 == 2) { return undef; }
                    439: 	return $1;
                    440:     }
                    441:     return undef;
                    442: }
                    443: 
1.783     albertel  444: sub convert_and_load_session_env {
                    445:     my ($lonidsdir,$handle)=@_;
                    446:     my @profile;
                    447:     {
1.917     albertel  448: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    449: 	if (!$opened) {
1.915     albertel  450: 	    return 0;
                    451: 	}
1.783     albertel  452: 	flock($idf,LOCK_SH);
                    453: 	@profile=<$idf>;
                    454: 	close($idf);
                    455:     }
                    456:     my %temp_env;
                    457:     foreach my $line (@profile) {
1.786     albertel  458: 	if ($line !~ m/=/) {
                    459: 	    return 0;
                    460: 	}
1.783     albertel  461: 	chomp($line);
                    462: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    463: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    464:     }
                    465:     unlink("$lonidsdir/$handle.id");
                    466:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    467: 	    0640)) {
                    468: 	%disk_env = %temp_env;
                    469: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    470: 	untie(%disk_env);
                    471:     }
1.786     albertel  472:     return 1;
1.783     albertel  473: }
                    474: 
1.374     www       475: # ------------------------------------------- Transfer profile into environment
1.780     albertel  476: my $env_loaded;
                    477: sub transfer_profile_to_env {
1.788     albertel  478:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    479:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       480: 
1.720     albertel  481:     if (!defined($lonidsdir)) {
                    482: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    483:     }
                    484:     if (!defined($handle)) {
                    485:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    486:     }
                    487: 
1.786     albertel  488:     my $convert;
                    489:     {
1.917     albertel  490:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    491: 	if (!$opened) {
1.915     albertel  492: 	    return;
                    493: 	}
1.786     albertel  494: 	flock($idf,LOCK_SH);
                    495: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    496: 		&GDBM_READER(),0640)) {
                    497: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    498: 	    untie(%disk_env);
                    499: 	} else {
                    500: 	    $convert = 1;
                    501: 	}
                    502:     }
                    503:     if ($convert) {
                    504: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    505: 	    &logthis("Failed to load session, or convert session.");
                    506: 	}
1.374     www       507:     }
1.783     albertel  508: 
1.786     albertel  509:     my %remove;
1.783     albertel  510:     while ( my $envname = each(%env) ) {
1.433     matthew   511:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    512:             if ($time < time-300) {
1.783     albertel  513:                 $remove{$key}++;
1.433     matthew   514:             }
                    515:         }
                    516:     }
1.783     albertel  517: 
1.619     albertel  518:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  519:     $env_loaded=1;
1.783     albertel  520:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   521:         &delenv($expired_key);
1.374     www       522:     }
1.1       albertel  523: }
                    524: 
1.916     albertel  525: # ---------------------------------------------------- Check for valid session 
                    526: sub check_for_valid_session {
                    527:     my ($r) = @_;
                    528:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    529:     my $lonid=$cookies{'lonID'};
                    530:     return undef if (!$lonid);
                    531: 
                    532:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    533:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    534:     return undef if (!-e "$lonidsdir/$handle.id");
                    535: 
1.917     albertel  536:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    537:     return undef if (!$opened);
1.916     albertel  538: 
                    539:     flock($idf,LOCK_SH);
                    540:     my %disk_env;
                    541:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    542: 	    &GDBM_READER(),0640)) {
                    543: 	return undef;	
                    544:     }
                    545: 
                    546:     if (!defined($disk_env{'user.name'})
                    547: 	|| !defined($disk_env{'user.domain'})) {
                    548: 	return undef;
                    549:     }
                    550:     return $handle;
                    551: }
                    552: 
1.830     albertel  553: sub timed_flock {
                    554:     my ($file,$lock_type) = @_;
                    555:     my $failed=0;
                    556:     eval {
                    557: 	local $SIG{__DIE__}='DEFAULT';
                    558: 	local $SIG{ALRM}=sub {
                    559: 	    $failed=1;
                    560: 	    die("failed lock");
                    561: 	};
                    562: 	alarm(13);
                    563: 	flock($file,$lock_type);
                    564: 	alarm(0);
                    565:     };
                    566:     if ($failed) {
                    567: 	return undef;
                    568:     } else {
                    569: 	return 1;
                    570:     }
                    571: }
                    572: 
1.5       www       573: # ---------------------------------------------------------- Append Environment
                    574: 
                    575: sub appenv {
1.949     raeburn   576:     my ($newenv,$roles) = @_;
                    577:     if (ref($newenv) eq 'HASH') {
                    578:         foreach my $key (keys(%{$newenv})) {
                    579:             my $refused = 0;
                    580: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    581:                 $refused = 1;
                    582:                 if (ref($roles) eq 'ARRAY') {
                    583:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    584:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    585:                         $refused = 0;
                    586:                     }
                    587:                 }
                    588:             }
                    589:             if ($refused) {
                    590:                 &logthis("<font color=\"blue\">WARNING: ".
                    591:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    592:                          .'</font>');
                    593: 	        delete($newenv->{$key});
                    594:             } else {
                    595:                 $env{$key}=$newenv->{$key};
                    596:             }
                    597:         }
                    598:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    599:         if ($opened
                    600: 	    && &timed_flock($env_file,LOCK_EX)
                    601: 	    &&
                    602: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    603: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    604: 	    while (my ($key,$value) = each(%{$newenv})) {
                    605: 	        $disk_env{$key} = $value;
                    606: 	    }
                    607: 	    untie(%disk_env);
1.35      www       608:         }
1.191     harris41  609:     }
1.56      www       610:     return 'ok';
                    611: }
                    612: # ----------------------------------------------------- Delete from Environment
                    613: 
                    614: sub delenv {
1.987     raeburn   615:     my ($delthis,$regexp) = @_;
1.56      www       616:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  617:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       618:                 "Attempt to delete from environment ".$delthis);
                    619:         return 'error';
                    620:     }
1.917     albertel  621:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    622:     if ($opened
1.915     albertel  623: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  624: 	&&
                    625: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    626: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  627: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   628: 	    if ($regexp) {
                    629:                 if ($key=~/^$delthis/) {
                    630:                     delete($env{$key});
                    631:                     delete($disk_env{$key});
                    632:                 } 
                    633:             } else {
                    634:                 if ($key=~/^\Q$delthis\E/) {
                    635: 		    delete($env{$key});
                    636: 		    delete($disk_env{$key});
                    637: 	        }
                    638:             }
1.448     albertel  639: 	}
1.783     albertel  640: 	untie(%disk_env);
1.5       www       641:     }
                    642:     return 'ok';
1.369     albertel  643: }
                    644: 
1.790     albertel  645: sub get_env_multiple {
                    646:     my ($name) = @_;
                    647:     my @values;
                    648:     if (defined($env{$name})) {
                    649:         # exists is it an array
                    650:         if (ref($env{$name})) {
                    651:             @values=@{ $env{$name} };
                    652:         } else {
                    653:             $values[0]=$env{$name};
                    654:         }
                    655:     }
                    656:     return(@values);
                    657: }
                    658: 
1.958     www       659: # ------------------------------------------------------------------- Locking
                    660: 
                    661: sub set_lock {
                    662:     my ($text)=@_;
                    663:     $locknum++;
                    664:     my $id=$$.'-'.$locknum;
                    665:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    666:              'session.lock.'.$id => $text});
                    667:     return $id;
                    668: }
                    669: 
                    670: sub get_locks {
                    671:     my $num=0;
                    672:     my %texts=();
                    673:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    674:        if ($lock=~/\w/) {
                    675:           $num++;
                    676:           $texts{$lock}=$env{'session.lock.'.$lock};
                    677:        }
                    678:    }
                    679:    return ($num,%texts);
                    680: }
                    681: 
                    682: sub remove_lock {
                    683:     my ($id)=@_;
                    684:     my $newlocks='';
                    685:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    686:        if (($lock=~/\w/) && ($lock ne $id)) {
                    687:           $newlocks.=','.$lock;
                    688:        }
                    689:     }
                    690:     &appenv({'session.locks' => $newlocks});
                    691:     &delenv('session.lock.'.$id);
                    692: }
                    693: 
                    694: sub remove_all_locks {
                    695:     my $activelocks=$env{'session.locks'};
                    696:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    697:        if ($lock=~/\w/) {
                    698:           &remove_lock($lock);
                    699:        }
                    700:     }
                    701: }
                    702: 
                    703: 
1.369     albertel  704: # ------------------------------------------ Find out current server userload
                    705: sub userload {
                    706:     my $numusers=0;
                    707:     {
                    708: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    709: 	my $filename;
                    710: 	my $curtime=time;
                    711: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  712: 	    next if ($filename eq '.' || $filename eq '..');
                    713: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  714: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  715: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  716: 	}
                    717: 	closedir(LONIDS);
                    718:     }
                    719:     my $userloadpercent=0;
                    720:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    721:     if ($maxuserload) {
1.371     albertel  722: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  723:     }
1.372     albertel  724:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  725:     return $userloadpercent;
1.283     www       726: }
                    727: 
                    728: # ------------------------------------------ Fight off request when overloaded
                    729: 
                    730: sub overloaderror {
                    731:     my ($r,$checkserver)=@_;
                    732:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    733:     my $loadavg;
                    734:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  735:        open(my $loadfile,'/proc/loadavg');
1.283     www       736:        $loadavg=<$loadfile>;
                    737:        $loadavg =~ s/\s.*//g;
1.285     matthew   738:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  739:        close($loadfile);
1.283     www       740:     } else {
                    741:        $loadavg=&reply('load',$checkserver);
                    742:     }
1.285     matthew   743:     my $overload=$loadavg-100;
1.283     www       744:     if ($overload>0) {
1.285     matthew   745: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       746:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       747:         return 413;
1.283     www       748:     }    
                    749:     return '';
1.5       www       750: }
1.1       albertel  751: 
                    752: # ------------------------------ Find server with least workload from spare.tab
1.11      www       753: 
1.1       albertel  754: sub spareserver {
1.670     albertel  755:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  756:     my $spare_server;
1.370     albertel  757:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  758:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    759:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   760:     my ($uint_dom,$remotesessions);
                    761:     if ($env{'user.domain'}) {
                    762:         my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
                    763:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    764:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                    765:         $remotesessions = $udomdefaults{'remotesessions'};
                    766:     }
1.784     albertel  767:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   768:         if ($uint_dom) {
                    769:             next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    770:                                          $remotesessions,$try_server));
                    771:         }
1.784     albertel  772: 	($spare_server, $lowest_load) =
                    773: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    774:     }
                    775: 
                    776:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    777: 
                    778:     if (!$found_server) {
                    779: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   780:             if ($uint_dom) {
                    781:                 next unless (&spare_can_host($env{'user.domain'},$uint_dom,
                    782:                                              $remotesessions,$try_server));
                    783:             }
1.784     albertel  784: 	    ($spare_server, $lowest_load) =
                    785: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    786: 	}
                    787:     }
                    788: 
                    789:     if (!$want_server_name) {
1.968     raeburn   790:         my $protocol = 'http';
                    791:         if ($protocol{$spare_server} eq 'https') {
                    792:             $protocol = $protocol{$spare_server};
                    793:         }
1.1001    raeburn   794:         if (defined($spare_server)) {
                    795:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   796:             if (defined($hostname)) {
1.1001    raeburn   797: 	        $spare_server = $protocol.'://'.$hostname;
                    798:             }
                    799:         }
1.784     albertel  800:     }
                    801:     return $spare_server;
                    802: }
                    803: 
                    804: sub compare_server_load {
                    805:     my ($try_server, $spare_server, $lowest_load) = @_;
                    806: 
                    807:     my $loadans     = &reply('load',    $try_server);
                    808:     my $userloadans = &reply('userload',$try_server);
                    809: 
                    810:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3  raeburn   811:         return; #didn't get a number from the server
1.784     albertel  812:     }
                    813: 
                    814:     my $load;
                    815:     if ($loadans =~ /\d/) {
                    816: 	if ($userloadans =~ /\d/) {
                    817: 	    #both are numbers, pick the bigger one
                    818: 	    $load = ($loadans > $userloadans) ? $loadans 
                    819: 		                              : $userloadans;
1.411     albertel  820: 	} else {
1.784     albertel  821: 	    $load = $loadans;
1.411     albertel  822: 	}
1.784     albertel  823:     } else {
                    824: 	$load = $userloadans;
                    825:     }
                    826: 
                    827:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    828: 	$spare_server = $try_server;
                    829: 	$lowest_load  = $load;
1.370     albertel  830:     }
1.784     albertel  831:     return ($spare_server,$lowest_load);
1.202     matthew   832: }
1.914     albertel  833: 
                    834: # --------------------------- ask offload servers if user already has a session
                    835: sub find_existing_session {
                    836:     my ($udom,$uname) = @_;
                    837:     foreach my $try_server (@{ $spareid{'primary'} },
                    838: 			    @{ $spareid{'default'} }) {
                    839: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    840:     }
                    841:     return;
                    842: }
                    843: 
                    844: # -------------------------------- ask if server already has a session for user
                    845: sub has_user_session {
                    846:     my ($lonid,$udom,$uname) = @_;
                    847:     my $result = &reply(join(':','userhassession',
                    848: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    849:     return 1 if ($result eq 'ok');
                    850: 
                    851:     return 0;
                    852: }
                    853: 
1.1056.4.3  raeburn   854: # --------- determine least loaded server in a user's domain which allows login
                    855: 
                    856: sub choose_server {
                    857:     my ($udom) = @_;
                    858:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    859:     my %servers = &get_servers($udom);
                    860:     my $lowest_load = 30000;
                    861:     my ($login_host,$hostname);
                    862:     foreach my $lonhost (keys(%servers)) {
                    863:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    864:         if ($loginvia eq '') {
                    865:             ($login_host, $lowest_load) =
                    866:             &compare_server_load($lonhost, $login_host, $lowest_load);
                    867:         }
                    868:     }
                    869:     if ($login_host ne '') {
                    870:         $hostname = $servers{$login_host};
                    871:     }
                    872:     return ($login_host,$hostname);
                    873: }
                    874: 
1.202     matthew   875: # --------------------------------------------- Try to change a user's password
                    876: 
                    877: sub changepass {
1.799     raeburn   878:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   879:     $currentpass = &escape($currentpass);
                    880:     $newpass     = &escape($newpass);
1.1030    raeburn   881:     my $lonhost = $perlvar{'lonHostID'};
                    882:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   883: 		       $server);
                    884:     if (! $answer) {
                    885: 	&logthis("No reply on password change request to $server ".
                    886: 		 "by $uname in domain $udom.");
                    887:     } elsif ($answer =~ "^ok") {
                    888:         &logthis("$uname in $udom successfully changed their password ".
                    889: 		 "on $server.");
                    890:     } elsif ($answer =~ "^pwchange_failure") {
                    891: 	&logthis("$uname in $udom was unable to change their password ".
                    892: 		 "on $server.  The action was blocked by either lcpasswd ".
                    893: 		 "or pwchange");
                    894:     } elsif ($answer =~ "^non_authorized") {
                    895:         &logthis("$uname in $udom did not get their password correct when ".
                    896: 		 "attempting to change it on $server.");
                    897:     } elsif ($answer =~ "^auth_mode_error") {
                    898:         &logthis("$uname in $udom attempted to change their password despite ".
                    899: 		 "not being locally or internally authenticated on $server.");
                    900:     } elsif ($answer =~ "^unknown_user") {
                    901:         &logthis("$uname in $udom attempted to change their password ".
                    902: 		 "on $server but were unable to because $server is not ".
                    903: 		 "their home server.");
                    904:     } elsif ($answer =~ "^refused") {
                    905: 	&logthis("$server refused to change $uname in $udom password because ".
                    906: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   907:     } elsif ($answer =~ "invalid_client") {
                    908:         &logthis("$server refused to change $uname in $udom password because ".
                    909:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   910:     }
                    911:     return $answer;
1.1       albertel  912: }
                    913: 
1.169     harris41  914: # ----------------------- Try to determine user's current authentication scheme
                    915: 
                    916: sub queryauthenticate {
                    917:     my ($uname,$udom)=@_;
1.456     albertel  918:     my $uhome=&homeserver($uname,$udom);
                    919:     if (!$uhome) {
                    920: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    921: 	return 'no_host';
                    922:     }
                    923:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    924:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    925: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  926:     }
1.456     albertel  927:     return $answer;
1.169     harris41  928: }
                    929: 
1.1       albertel  930: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       931: 
1.1       albertel  932: sub authenticate {
1.1056.4.3  raeburn   933:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  934:     $upass=&escape($upass);
                    935:     $uname= &LONCAPA::clean_username($uname);
1.836     www       936:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   937:     my $newhome;
1.836     www       938:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    939: # Maybe the machine was offline and only re-appeared again recently?
                    940:         &reconlonc();
                    941: # One more
1.952     raeburn   942: 	$uhome=&homeserver($uname,$udom,1);
                    943:         if (($uhome eq 'no_host') && $checkdefauth) {
                    944:             if (defined(&domain($udom,'primary'))) {
                    945:                 $newhome=&domain($udom,'primary');
                    946:             }
                    947:             if ($newhome ne '') {
                    948:                 $uhome = $newhome;
                    949:             }
                    950:         }
1.836     www       951: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    952: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   953: 	    return 'no_host';
                    954:         }
1.1       albertel  955:     }
1.1056.4.3  raeburn   956:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  957:     if ($answer eq 'authorized') {
1.952     raeburn   958:         if ($newhome) {
                    959:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    960:             return 'no_account_on_host'; 
                    961:         } else {
                    962:             &logthis("User $uname at $udom authorized by $uhome");
                    963:             return $uhome;
                    964:         }
1.471     albertel  965:     }
                    966:     if ($answer eq 'non_authorized') {
                    967: 	&logthis("User $uname at $udom rejected by $uhome");
                    968: 	return 'no_host'; 
1.9       www       969:     }
1.471     albertel  970:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  971:     return 'no_host';
                    972: }
                    973: 
1.1056.4.3  raeburn   974: sub can_host_session {
                    975:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                    976:     my $canhost = 1;
                    977:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                    978:     if (ref($remotesessions) eq 'HASH') {
                    979:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                    980:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                    981:                 $canhost = 0;
                    982:             } else {
                    983:                 $canhost = 1;
                    984:             }
                    985:         }
                    986:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                    987:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                    988:                 $canhost = 1;
                    989:             } else {
                    990:                 $canhost = 0;
                    991:             }
                    992:         }
                    993:         if ($canhost) {
                    994:             if ($remotesessions->{'version'} ne '') {
                    995:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                    996:                 if ($reqmajor ne '' && $reqminor ne '') {
                    997:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                    998:                         my $major = $1;
                    999:                         my $minor = $2;
                   1000:                         if (($major < $reqmajor ) ||
                   1001:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1002:                             $canhost = 0;
                   1003:                         }
                   1004:                     } else {
                   1005:                         $canhost = 0;
                   1006:                     }
                   1007:                 }
                   1008:             }
                   1009:         }
                   1010:     }
                   1011:     if ($canhost) {
                   1012:         if (ref($hostedsessions) eq 'HASH') {
                   1013:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
                   1014:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
                   1015:                     $canhost = 0;
                   1016:                 } else {
                   1017:                     $canhost = 1;
                   1018:                 }
                   1019:             }
                   1020:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
                   1021:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
                   1022:                     $canhost = 1;
                   1023:                 } else {
                   1024:                     $canhost = 0;
                   1025:                 }
                   1026:             }
                   1027:         }
                   1028:     }
                   1029:     return $canhost;
                   1030: }
                   1031: 
1.1056.4.8  raeburn  1032: sub spare_can_host {
                   1033:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1034:     my $canhost=1;
                   1035:     my @intdoms;
                   1036:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1037:     if (ref($internet_names) eq 'ARRAY') {
                   1038:         @intdoms = @{$internet_names};
                   1039:     }
                   1040:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1041:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1042:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1043:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1044:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1045:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1046:                                      $remotesessions,
                   1047:                                      $defdomdefaults{'hostedsessions'});
                   1048:     }
                   1049:     return $canhost;
                   1050: }
                   1051: 
1.1       albertel 1052: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1053: 
1.599     albertel 1054: my %homecache;
1.1       albertel 1055: sub homeserver {
1.230     stredwic 1056:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1057:     my $index="$uname:$udom";
1.426     albertel 1058: 
1.599     albertel 1059:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1060: 
                   1061:     my %servers = &get_servers($udom,'library');
                   1062:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1063:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1064: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1065: 
                   1066: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1067: 	if ($answer eq 'found') {
                   1068: 	    delete($badServerCache{$tryserver}); 
                   1069: 	    return $homecache{$index}=$tryserver;
                   1070: 	} elsif ($answer eq 'no_host') {
                   1071: 	    $badServerCache{$tryserver}=1;
                   1072: 	}
1.1       albertel 1073:     }    
                   1074:     return 'no_host';
1.70      www      1075: }
                   1076: 
                   1077: # ------------------------------------- Find the usernames behind a list of IDs
                   1078: 
                   1079: sub idget {
                   1080:     my ($udom,@ids)=@_;
                   1081:     my %returnhash=();
                   1082:     
1.841     albertel 1083:     my %servers = &get_servers($udom,'library');
                   1084:     foreach my $tryserver (keys(%servers)) {
                   1085: 	my $idlist=join('&',@ids);
                   1086: 	$idlist=~tr/A-Z/a-z/; 
                   1087: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1088: 	my @answer=();
                   1089: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1090: 	    @answer=split(/\&/,$reply);
                   1091: 	}                    ;
                   1092: 	my $i;
                   1093: 	for ($i=0;$i<=$#ids;$i++) {
                   1094: 	    if ($answer[$i]) {
                   1095: 		$returnhash{$ids[$i]}=$answer[$i];
                   1096: 	    } 
                   1097: 	}
                   1098:     } 
1.70      www      1099:     return %returnhash;
                   1100: }
                   1101: 
                   1102: # ------------------------------------- Find the IDs behind a list of usernames
                   1103: 
                   1104: sub idrget {
                   1105:     my ($udom,@unames)=@_;
                   1106:     my %returnhash=();
1.800     albertel 1107:     foreach my $uname (@unames) {
                   1108:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1109:     }
1.70      www      1110:     return %returnhash;
                   1111: }
                   1112: 
                   1113: # ------------------------------- Store away a list of names and associated IDs
                   1114: 
                   1115: sub idput {
                   1116:     my ($udom,%ids)=@_;
                   1117:     my %servers=();
1.800     albertel 1118:     foreach my $uname (keys(%ids)) {
                   1119: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1120:         my $uhom=&homeserver($uname,$udom);
1.70      www      1121:         if ($uhom ne 'no_host') {
1.800     albertel 1122:             my $id=&escape($ids{$uname});
1.70      www      1123:             $id=~tr/A-Z/a-z/;
1.800     albertel 1124:             my $esc_unam=&escape($uname);
1.70      www      1125: 	    if ($servers{$uhom}) {
1.800     albertel 1126: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1127:             } else {
1.800     albertel 1128:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1129:             }
                   1130:         }
1.191     harris41 1131:     }
1.800     albertel 1132:     foreach my $server (keys(%servers)) {
                   1133:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1134:     }
1.344     www      1135: }
                   1136: 
1.1023    raeburn  1137: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1138: sub dump_dom {
1.1023    raeburn  1139:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1140:     if (!$udom) {
                   1141:         $udom=$env{'user.domain'};
                   1142:     }
                   1143:     my %returnhash;
1.1023    raeburn  1144:     if ($udom) {
                   1145:         my $uname = &get_domainconfiguser($udom);
                   1146:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1147:     }
                   1148:     return %returnhash;
                   1149: }
                   1150: 
1.1023    raeburn  1151: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1152: 
                   1153: sub get_dom {
1.860     raeburn  1154:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1155:     my $items='';
                   1156:     foreach my $item (@$storearr) {
                   1157:         $items.=&escape($item).'&';
                   1158:     }
                   1159:     $items=~s/\&$//;
1.860     raeburn  1160:     if (!$udom) {
                   1161:         $udom=$env{'user.domain'};
                   1162:         if (defined(&domain($udom,'primary'))) {
                   1163:             $uhome=&domain($udom,'primary');
                   1164:         } else {
1.874     albertel 1165:             undef($uhome);
1.860     raeburn  1166:         }
                   1167:     } else {
                   1168:         if (!$uhome) {
                   1169:             if (defined(&domain($udom,'primary'))) {
                   1170:                 $uhome=&domain($udom,'primary');
                   1171:             }
                   1172:         }
                   1173:     }
                   1174:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1175:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1176:         my %returnhash;
1.875     albertel 1177:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1178:             return %returnhash;
                   1179:         }
1.806     raeburn  1180:         my @pairs=split(/\&/,$rep);
                   1181:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1182:             return @pairs;
                   1183:         }
                   1184:         my $i=0;
                   1185:         foreach my $item (@$storearr) {
                   1186:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1187:             $i++;
                   1188:         }
                   1189:         return %returnhash;
                   1190:     } else {
1.880     banghart 1191:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1192:     }
                   1193: }
                   1194: 
                   1195: # -------------------------------------------- put items in domain db files 
                   1196: 
                   1197: sub put_dom {
1.860     raeburn  1198:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1199:     if (!$udom) {
                   1200:         $udom=$env{'user.domain'};
                   1201:         if (defined(&domain($udom,'primary'))) {
                   1202:             $uhome=&domain($udom,'primary');
                   1203:         } else {
1.874     albertel 1204:             undef($uhome);
1.860     raeburn  1205:         }
                   1206:     } else {
                   1207:         if (!$uhome) {
                   1208:             if (defined(&domain($udom,'primary'))) {
                   1209:                 $uhome=&domain($udom,'primary');
                   1210:             }
                   1211:         }
                   1212:     } 
                   1213:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1214:         my $items='';
                   1215:         foreach my $item (keys(%$storehash)) {
                   1216:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1217:         }
                   1218:         $items=~s/\&$//;
                   1219:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1220:     } else {
1.860     raeburn  1221:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1222:     }
                   1223: }
                   1224: 
1.1023    raeburn  1225: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1226: sub newput_dom {
1.1023    raeburn  1227:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1228:     my $result;
                   1229:     if (!$udom) {
                   1230:         $udom=$env{'user.domain'};
                   1231:     }
1.1023    raeburn  1232:     if ($udom) {
                   1233:         my $uname = &get_domainconfiguser($udom);
                   1234:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1235:     }
                   1236:     return $result;
                   1237: }
                   1238: 
1.1023    raeburn  1239: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1240: sub del_dom {
1.1023    raeburn  1241:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1242:     if (ref($storearr) eq 'ARRAY') {
                   1243:         if (!$udom) {
                   1244:             $udom=$env{'user.domain'};
                   1245:         }
1.1023    raeburn  1246:         if ($udom) {
                   1247:             my $uname = &get_domainconfiguser($udom); 
                   1248:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1249:         }
                   1250:     }
                   1251: }
                   1252: 
1.1023    raeburn  1253: # ----------------------------------construct domainconfig user for a domain 
                   1254: sub get_domainconfiguser {
                   1255:     my ($udom) = @_;
                   1256:     return $udom.'-domainconfig';
                   1257: }
                   1258: 
1.837     raeburn  1259: sub retrieve_inst_usertypes {
                   1260:     my ($udom) = @_;
                   1261:     my (%returnhash,@order);
1.989     raeburn  1262:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1263:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1264:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1265:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1266:         @order = @{$domdefs{'inststatusorder'}};
                   1267:     } else {
                   1268:         if (defined(&domain($udom,'primary'))) {
                   1269:             my $uhome=&domain($udom,'primary');
                   1270:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1271:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1272:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1273:                 return (\%returnhash,\@order);
                   1274:             }
                   1275:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1276:             my @pairs=split(/\&/,$hashitems);
                   1277:             foreach my $item (@pairs) {
                   1278:                 my ($key,$value)=split(/=/,$item,2);
                   1279:                 $key = &unescape($key);
                   1280:                 next if ($key =~ /^error: 2 /);
                   1281:                 $returnhash{$key}=&thaw_unescape($value);
                   1282:             }
                   1283:             my @esc_order = split(/\&/,$orderitems);
                   1284:             foreach my $item (@esc_order) {
                   1285:                 push(@order,&unescape($item));
                   1286:             }
                   1287:         } else {
                   1288:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1289:         }
                   1290:     }
                   1291:     return (\%returnhash,\@order);
                   1292: }
                   1293: 
1.868     raeburn  1294: sub is_domainimage {
                   1295:     my ($url) = @_;
                   1296:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1297:         if (&domain($1) ne '') {
                   1298:             return '1';
                   1299:         }
                   1300:     }
                   1301:     return;
                   1302: }
                   1303: 
1.899     raeburn  1304: sub inst_directory_query {
                   1305:     my ($srch) = @_;
                   1306:     my $udom = $srch->{'srchdomain'};
                   1307:     my %results;
                   1308:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1309:     my $outcome;
1.899     raeburn  1310:     if ($homeserver ne '') {
1.904     albertel 1311: 	my $queryid=&reply("querysend:instdirsearch:".
                   1312: 			   &escape($srch->{'srchby'}).':'.
                   1313: 			   &escape($srch->{'srchterm'}).':'.
                   1314: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1315: 	my $host=&hostname($homeserver);
                   1316: 	if ($queryid !~/^\Q$host\E\_/) {
                   1317: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1318: 	    return;
                   1319: 	}
                   1320: 	my $response = &get_query_reply($queryid);
                   1321: 	my $maxtries = 5;
                   1322: 	my $tries = 1;
                   1323: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1324: 	    $response = &get_query_reply($queryid);
                   1325: 	    $tries ++;
                   1326: 	}
                   1327: 
                   1328:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1329:             if ($response eq 'unavailable') {
                   1330:                 $outcome = $response;
                   1331:             } else {
                   1332:                 $outcome = 'ok';
                   1333:                 my @matches = split(/\n/,$response);
                   1334:                 foreach my $match (@matches) {
                   1335:                     my ($key,$value) = split(/=/,$match);
                   1336:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1337:                 }
1.899     raeburn  1338:             }
                   1339:         }
                   1340:     }
1.909     raeburn  1341:     return ($outcome,%results);
1.899     raeburn  1342: }
                   1343: 
                   1344: sub usersearch {
                   1345:     my ($srch) = @_;
                   1346:     my $dom = $srch->{'srchdomain'};
                   1347:     my %results;
                   1348:     my %libserv = &all_library();
                   1349:     my $query = 'usersearch';
                   1350:     foreach my $tryserver (keys(%libserv)) {
                   1351:         if (&host_domain($tryserver) eq $dom) {
                   1352:             my $host=&hostname($tryserver);
                   1353:             my $queryid=
1.911     raeburn  1354:                 &reply("querysend:".&escape($query).':'.
                   1355:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1356:                        &escape($srch->{'srchtype'}).':'.
                   1357:                        &escape($srch->{'srchterm'}),$tryserver);
                   1358:             if ($queryid !~/^\Q$host\E\_/) {
                   1359:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1360:                 next;
1.899     raeburn  1361:             }
                   1362:             my $reply = &get_query_reply($queryid);
                   1363:             my $maxtries = 1;
                   1364:             my $tries = 1;
                   1365:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1366:                 $reply = &get_query_reply($queryid);
                   1367:                 $tries ++;
                   1368:             }
                   1369:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1370:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1371:             } else {
1.911     raeburn  1372:                 my @matches;
                   1373:                 if ($reply =~ /\n/) {
                   1374:                     @matches = split(/\n/,$reply);
                   1375:                 } else {
                   1376:                     @matches = split(/\&/,$reply);
                   1377:                 }
1.899     raeburn  1378:                 foreach my $match (@matches) {
                   1379:                     my ($uname,$udom,%userhash);
1.911     raeburn  1380:                     foreach my $entry (split(/:/,$match)) {
                   1381:                         my ($key,$value) =
                   1382:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1383:                         $userhash{$key} = $value;
                   1384:                         if ($key eq 'username') {
                   1385:                             $uname = $value;
                   1386:                         } elsif ($key eq 'domain') {
                   1387:                             $udom = $value;
1.911     raeburn  1388:                         }
1.899     raeburn  1389:                     }
                   1390:                     $results{$uname.':'.$udom} = \%userhash;
                   1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
                   1395:     return %results;
                   1396: }
                   1397: 
1.912     raeburn  1398: sub get_instuser {
                   1399:     my ($udom,$uname,$id) = @_;
                   1400:     my $homeserver = &domain($udom,'primary');
                   1401:     my ($outcome,%results);
                   1402:     if ($homeserver ne '') {
                   1403:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1404:                            &escape($id).':'.&escape($udom),$homeserver);
                   1405:         my $host=&hostname($homeserver);
                   1406:         if ($queryid !~/^\Q$host\E\_/) {
                   1407:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1408:             return;
                   1409:         }
                   1410:         my $response = &get_query_reply($queryid);
                   1411:         my $maxtries = 5;
                   1412:         my $tries = 1;
                   1413:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1414:             $response = &get_query_reply($queryid);
                   1415:             $tries ++;
                   1416:         }
                   1417:         if (!&error($response) && $response ne 'refused') {
                   1418:             if ($response eq 'unavailable') {
                   1419:                 $outcome = $response;
                   1420:             } else {
                   1421:                 $outcome = 'ok';
                   1422:                 my @matches = split(/\n/,$response);
                   1423:                 foreach my $match (@matches) {
                   1424:                     my ($key,$value) = split(/=/,$match);
                   1425:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1426:                 }
                   1427:             }
                   1428:         }
                   1429:     }
                   1430:     my %userinfo;
                   1431:     if (ref($results{$uname}) eq 'HASH') {
                   1432:         %userinfo = %{$results{$uname}};
                   1433:     } 
                   1434:     return ($outcome,%userinfo);
                   1435: }
                   1436: 
                   1437: sub inst_rulecheck {
1.923     raeburn  1438:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1439:     my %returnhash;
                   1440:     if ($udom ne '') {
                   1441:         if (ref($rules) eq 'ARRAY') {
                   1442:             @{$rules} = map {&escape($_);} (@{$rules});
                   1443:             my $rulestr = join(':',@{$rules});
                   1444:             my $homeserver=&domain($udom,'primary');
                   1445:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1446:                 my $response;
                   1447:                 if ($item eq 'username') {                
                   1448:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1449:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1450:                                               $homeserver));
1.923     raeburn  1451:                 } elsif ($item eq 'id') {
                   1452:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1453:                                               ':'.&escape($id).':'.$rulestr,
                   1454:                                               $homeserver));
1.945     raeburn  1455:                 } elsif ($item eq 'selfcreate') {
                   1456:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1457:                                                &escape($udom).':'.&escape($uname).
                   1458:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1459:                 }
1.912     raeburn  1460:                 if ($response ne 'refused') {
                   1461:                     my @pairs=split(/\&/,$response);
                   1462:                     foreach my $item (@pairs) {
                   1463:                         my ($key,$value)=split(/=/,$item,2);
                   1464:                         $key = &unescape($key);
                   1465:                         next if ($key =~ /^error: 2 /);
                   1466:                         $returnhash{$key}=&thaw_unescape($value);
                   1467:                     }
                   1468:                 }
                   1469:             }
                   1470:         }
                   1471:     }
                   1472:     return %returnhash;
                   1473: }
                   1474: 
                   1475: sub inst_userrules {
1.923     raeburn  1476:     my ($udom,$check) = @_;
1.912     raeburn  1477:     my (%ruleshash,@ruleorder);
                   1478:     if ($udom ne '') {
                   1479:         my $homeserver=&domain($udom,'primary');
                   1480:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1481:             my $response;
                   1482:             if ($check eq 'id') {
                   1483:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1484:                                  $homeserver);
1.943     raeburn  1485:             } elsif ($check eq 'email') {
                   1486:                 $response=&reply('instemailrules:'.&escape($udom),
                   1487:                                  $homeserver);
1.923     raeburn  1488:             } else {
                   1489:                 $response=&reply('instuserrules:'.&escape($udom),
                   1490:                                  $homeserver);
                   1491:             }
1.912     raeburn  1492:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1493:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1494:                 ($response ne 'no_such_host')) {
                   1495:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1496:                 my @pairs=split(/\&/,$hashitems);
                   1497:                 foreach my $item (@pairs) {
                   1498:                     my ($key,$value)=split(/=/,$item,2);
                   1499:                     $key = &unescape($key);
                   1500:                     next if ($key =~ /^error: 2 /);
                   1501:                     $ruleshash{$key}=&thaw_unescape($value);
                   1502:                 }
                   1503:                 my @esc_order = split(/\&/,$orderitems);
                   1504:                 foreach my $item (@esc_order) {
                   1505:                     push(@ruleorder,&unescape($item));
                   1506:                 }
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return (\%ruleshash,\@ruleorder);
                   1511: }
                   1512: 
1.976     raeburn  1513: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1514: 
                   1515: sub get_domain_defaults {
                   1516:     my ($domain) = @_;
                   1517:     my $cachetime = 60*60*24;
                   1518:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1519:     if (defined($cached)) {
                   1520:         if (ref($result) eq 'HASH') {
                   1521:             return %{$result};
                   1522:         }
                   1523:     }
                   1524:     my %domdefaults;
                   1525:     my %domconfig =
1.989     raeburn  1526:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1527:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1528:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1529:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1530:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1531:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1532:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1533:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1534:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1535:     } else {
                   1536:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1537:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1538:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1539:     }
1.976     raeburn  1540:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1541:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1542:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1543:         } else {
                   1544:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1545:         } 
                   1546:         my @usertools = ('aboutme','blog','portfolio');
                   1547:         foreach my $item (@usertools) {
                   1548:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1549:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1550:             }
                   1551:         }
                   1552:     }
1.985     raeburn  1553:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1554:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1555:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1556:         }
                   1557:     }
1.989     raeburn  1558:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1559:         foreach my $item ('inststatustypes','inststatusorder') {
                   1560:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1561:         }
                   1562:     }
1.1047    raeburn  1563:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1564:         foreach my $item ('canuse_pdfforms') {
                   1565:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1566:         }
                   1567:     }
1.1056.4.3  raeburn  1568:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1569:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1570:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1571:         }
                   1572:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1573:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1574:         }
                   1575:     }
1.943     raeburn  1576:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1577:                                   $cachetime);
                   1578:     return %domdefaults;
                   1579: }
                   1580: 
1.344     www      1581: # --------------------------------------------------- Assign a key to a student
                   1582: 
                   1583: sub assign_access_key {
1.364     www      1584: #
                   1585: # a valid key looks like uname:udom#comments
                   1586: # comments are being appended
                   1587: #
1.498     www      1588:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1589:     $kdom=
1.620     albertel 1590:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1591:     $knum=
1.620     albertel 1592:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1593:     $cdom=
1.620     albertel 1594:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1595:     $cnum=
1.620     albertel 1596:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1597:     $udom=$env{'user.name'} unless (defined($udom));
                   1598:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1599:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1600:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1601:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1602:                                                   # assigned to this person
                   1603:                                                   # - this should not happen,
1.345     www      1604:                                                   # unless something went wrong
                   1605:                                                   # the first time around
                   1606: # ready to assign
1.364     www      1607:         $logentry=$1.'; '.$logentry;
1.496     www      1608:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1609:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1610: # key now belongs to user
1.346     www      1611: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1612:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1613:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1614:                 return 'ok';
                   1615:             } else {
                   1616:                 return 
                   1617:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1618: 	    }
                   1619:         } else {
                   1620:             return 'error: Could not assign key, try again later.';
                   1621:         }
1.364     www      1622:     } elsif (!$existing{$ckey}) {
1.345     www      1623: # the key does not exist
                   1624: 	return 'error: The key does not exist';
                   1625:     } else {
                   1626: # the key is somebody else's
                   1627: 	return 'error: The key is already in use';
                   1628:     }
1.344     www      1629: }
                   1630: 
1.364     www      1631: # ------------------------------------------ put an additional comment on a key
                   1632: 
                   1633: sub comment_access_key {
                   1634: #
                   1635: # a valid key looks like uname:udom#comments
                   1636: # comments are being appended
                   1637: #
                   1638:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1639:     $cdom=
1.620     albertel 1640:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1641:     $cnum=
1.620     albertel 1642:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1643:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1644:     if ($existing{$ckey}) {
                   1645:         $existing{$ckey}.='; '.$logentry;
                   1646: # ready to assign
1.367     www      1647:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1648:                                                  $cdom,$cnum) eq 'ok') {
                   1649: 	    return 'ok';
                   1650:         } else {
                   1651: 	    return 'error: Count not store comment.';
                   1652:         }
                   1653:     } else {
                   1654: # the key does not exist
                   1655: 	return 'error: The key does not exist';
                   1656:     }
                   1657: }
                   1658: 
1.344     www      1659: # ------------------------------------------------------ Generate a set of keys
                   1660: 
                   1661: sub generate_access_keys {
1.364     www      1662:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1663:     $cdom=
1.620     albertel 1664:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1665:     $cnum=
1.620     albertel 1666:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1667:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1668:     unless (($cdom) && ($cnum)) { return 0; }
                   1669:     if ($number>10000) { return 0; }
                   1670:     sleep(2); # make sure don't get same seed twice
                   1671:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1672:     my $total=0;
                   1673:     for (my $i=1;$i<=$number;$i++) {
                   1674:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1675:                   sprintf("%lx",int(100000*rand)).'-'.
                   1676:                   sprintf("%lx",int(100000*rand));
                   1677:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1678:        $newkey=~s/0/h/g; # and also 0 and O
                   1679:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1680:        if ($existing{$newkey}) {
                   1681:            $i--;
                   1682:        } else {
1.364     www      1683: 	  if (&put('accesskeys',
                   1684:               { $newkey => '# generated '.localtime().
1.620     albertel 1685:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1686:                            '; '.$logentry },
                   1687: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1688:               $total++;
                   1689: 	  }
                   1690:        }
                   1691:     }
1.620     albertel 1692:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1693:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1694:     return $total;
                   1695: }
                   1696: 
                   1697: # ------------------------------------------------------- Validate an accesskey
                   1698: 
                   1699: sub validate_access_key {
                   1700:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1701:     $cdom=
1.620     albertel 1702:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1703:     $cnum=
1.620     albertel 1704:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1705:     $udom=$env{'user.domain'} unless (defined($udom));
                   1706:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1707:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1708:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1709: }
                   1710: 
                   1711: # ------------------------------------- Find the section of student in a course
1.652     albertel 1712: sub devalidate_getsection_cache {
                   1713:     my ($udom,$unam,$courseid)=@_;
                   1714:     my $hashid="$udom:$unam:$courseid";
                   1715:     &devalidate_cache_new('getsection',$hashid);
                   1716: }
1.298     matthew  1717: 
1.815     albertel 1718: sub courseid_to_courseurl {
                   1719:     my ($courseid) = @_;
                   1720:     #already url style courseid
                   1721:     return $courseid if ($courseid =~ m{^/});
                   1722: 
                   1723:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1724: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1725: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1726: 	return "/$cdom/$cnum";
                   1727:     }
                   1728: 
                   1729:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1730:     if (exists($courseinfo{'num'})) {
                   1731: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1732:     }
                   1733: 
                   1734:     return undef;
                   1735: }
                   1736: 
1.298     matthew  1737: sub getsection {
                   1738:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1739:     my $cachetime=1800;
1.551     albertel 1740: 
                   1741:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1742:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1743:     if (defined($cached)) { return $result; }
                   1744: 
1.298     matthew  1745:     my %Pending; 
                   1746:     my %Expired;
                   1747:     #
                   1748:     # Each role can either have not started yet (pending), be active, 
                   1749:     #    or have expired.
                   1750:     #
                   1751:     # If there is an active role, we are done.
                   1752:     #
                   1753:     # If there is more than one role which has not started yet, 
                   1754:     #     choose the one which will start sooner
                   1755:     # If there is one role which has not started yet, return it.
                   1756:     #
                   1757:     # If there is more than one expired role, choose the one which ended last.
                   1758:     # If there is a role which has expired, return it.
                   1759:     #
1.815     albertel 1760:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  1761:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1762:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1763:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1764:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1765:         my $section=$1;
                   1766:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1767:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1768:         my $now=time;
1.548     albertel 1769:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1770:             $Expired{$end}=$section;
                   1771:             next;
                   1772:         }
1.548     albertel 1773:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1774:             $Pending{$start}=$section;
                   1775:             next;
                   1776:         }
1.599     albertel 1777:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1778:     }
                   1779:     #
                   1780:     # Presumedly there will be few matching roles from the above
                   1781:     # loop and the sorting time will be negligible.
                   1782:     if (scalar(keys(%Pending))) {
                   1783:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1784:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1785:     } 
                   1786:     if (scalar(keys(%Expired))) {
                   1787:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1788:         my $time = pop(@sorted);
1.599     albertel 1789:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1790:     }
1.599     albertel 1791:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1792: }
1.70      www      1793: 
1.599     albertel 1794: sub save_cache {
                   1795:     &purge_remembered();
1.722     albertel 1796:     #&Apache::loncommon::validate_page();
1.620     albertel 1797:     undef(%env);
1.780     albertel 1798:     undef($env_loaded);
1.599     albertel 1799: }
1.452     albertel 1800: 
1.599     albertel 1801: my $to_remember=-1;
                   1802: my %remembered;
                   1803: my %accessed;
                   1804: my $kicks=0;
                   1805: my $hits=0;
1.849     albertel 1806: sub make_key {
                   1807:     my ($name,$id) = @_;
1.872     albertel 1808:     if (length($id) > 65 
                   1809: 	&& length(&escape($id)) > 200) {
                   1810: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1811:     }
1.849     albertel 1812:     return &escape($name.':'.$id);
                   1813: }
                   1814: 
1.599     albertel 1815: sub devalidate_cache_new {
                   1816:     my ($name,$id,$debug) = @_;
                   1817:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1818:     $id=&make_key($name,$id);
1.599     albertel 1819:     $memcache->delete($id);
                   1820:     delete($remembered{$id});
                   1821:     delete($accessed{$id});
                   1822: }
                   1823: 
                   1824: sub is_cached_new {
                   1825:     my ($name,$id,$debug) = @_;
1.849     albertel 1826:     $id=&make_key($name,$id);
1.599     albertel 1827:     if (exists($remembered{$id})) {
                   1828: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1829: 	$accessed{$id}=[&gettimeofday()];
                   1830: 	$hits++;
                   1831: 	return ($remembered{$id},1);
                   1832:     }
                   1833:     my $value = $memcache->get($id);
                   1834:     if (!(defined($value))) {
                   1835: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1836: 	return (undef,undef);
1.416     albertel 1837:     }
1.599     albertel 1838:     if ($value eq '__undef__') {
                   1839: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1840: 	$value=undef;
                   1841:     }
                   1842:     &make_room($id,$value,$debug);
                   1843:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1844:     return ($value,1);
                   1845: }
                   1846: 
                   1847: sub do_cache_new {
                   1848:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1849:     $id=&make_key($name,$id);
1.599     albertel 1850:     my $setvalue=$value;
                   1851:     if (!defined($setvalue)) {
                   1852: 	$setvalue='__undef__';
                   1853:     }
1.623     albertel 1854:     if (!defined($time) ) {
                   1855: 	$time=600;
                   1856:     }
1.599     albertel 1857:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1858:     my $result = $memcache->set($id,$setvalue,$time);
                   1859:     if (! $result) {
1.872     albertel 1860: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1861: 	$memcache->disconnect_all();
1.872     albertel 1862:     }
1.600     albertel 1863:     # need to make a copy of $value
1.919     albertel 1864:     &make_room($id,$value,$debug);
1.599     albertel 1865:     return $value;
                   1866: }
                   1867: 
                   1868: sub make_room {
                   1869:     my ($id,$value,$debug)=@_;
1.919     albertel 1870: 
                   1871:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1872:                                     : $value;
1.599     albertel 1873:     if ($to_remember<0) { return; }
                   1874:     $accessed{$id}=[&gettimeofday()];
                   1875:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1876:     my $to_kick;
                   1877:     my $max_time=0;
                   1878:     foreach my $other (keys(%accessed)) {
                   1879: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1880: 	    $to_kick=$other;
                   1881: 	    $max_time=&tv_interval($accessed{$other});
                   1882: 	}
                   1883:     }
                   1884:     delete($remembered{$to_kick});
                   1885:     delete($accessed{$to_kick});
                   1886:     $kicks++;
                   1887:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1888:     return;
                   1889: }
                   1890: 
1.599     albertel 1891: sub purge_remembered {
1.604     albertel 1892:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1893:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1894:     undef(%remembered);
                   1895:     undef(%accessed);
1.428     albertel 1896: }
1.70      www      1897: # ------------------------------------- Read an entry from a user's environment
                   1898: 
                   1899: sub userenvironment {
                   1900:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1901:     my $items;
                   1902:     foreach my $item (@what) {
                   1903:         $items.=&escape($item).'&';
                   1904:     }
                   1905:     $items=~s/\&$//;
1.70      www      1906:     my %returnhash=();
1.1009    raeburn  1907:     my $uhome = &homeserver($unam,$udom);
                   1908:     unless ($uhome eq 'no_host') {
                   1909:         my @answer=split(/\&/, 
                   1910:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1911:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1912:             return %returnhash;
                   1913:         }
1.1009    raeburn  1914:         my $i;
                   1915:         for ($i=0;$i<=$#what;$i++) {
                   1916: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1917:         }
1.70      www      1918:     }
                   1919:     return %returnhash;
1.1       albertel 1920: }
                   1921: 
1.617     albertel 1922: # ---------------------------------------------------------- Get a studentphoto
                   1923: sub studentphoto {
                   1924:     my ($udom,$unam,$ext) = @_;
                   1925:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1926:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1927:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1928:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1929:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1930:             } else {
                   1931:                 my ($result,$perm_reqd)=
1.707     albertel 1932: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1933:                 if ($result eq 'ok') {
                   1934:                     if (!($perm_reqd eq 'yes')) {
                   1935:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1936:                     }
                   1937:                 }
                   1938:             }
                   1939:         }
                   1940:     } else {
                   1941:         my ($result,$perm_reqd) = 
1.707     albertel 1942: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1943:         if ($result eq 'ok') {
                   1944:             if (!($perm_reqd eq 'yes')) {
                   1945:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1946:             }
                   1947:         }
                   1948:     }
                   1949:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1950: }
                   1951: 
                   1952: sub retrievestudentphoto {
                   1953:     my ($udom,$unam,$ext,$type) = @_;
                   1954:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1955:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1956:     if ($ret eq 'ok') {
                   1957:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1958:         if ($type eq 'thumbnail') {
                   1959:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1960:         }
                   1961:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1962:         return $tokenurl;
                   1963:     } else {
                   1964:         if ($type eq 'thumbnail') {
                   1965:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1966:         } else { 
                   1967:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1968:         }
1.617     albertel 1969:     }
                   1970: }
                   1971: 
1.263     www      1972: # -------------------------------------------------------------------- New chat
                   1973: 
                   1974: sub chatsend {
1.724     raeburn  1975:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1976:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1977:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1978:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1979:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1980: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1981: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1982: }
                   1983: 
                   1984: # ------------------------------------------ Find current version of a resource
                   1985: 
                   1986: sub getversion {
                   1987:     my $fname=&clutter(shift);
                   1988:     unless ($fname=~/^\/res\//) { return -1; }
                   1989:     return &currentversion(&filelocation('',$fname));
                   1990: }
                   1991: 
                   1992: sub currentversion {
                   1993:     my $fname=shift;
1.599     albertel 1994:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1995:     if (defined($cached)) { return $result; }
1.292     www      1996:     my $author=$fname;
                   1997:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1998:     my ($udom,$uname)=split(/\//,$author);
                   1999:     my $home=homeserver($uname,$udom);
                   2000:     if ($home eq 'no_host') { 
                   2001:         return -1; 
                   2002:     }
                   2003:     my $answer=reply("currentversion:$fname",$home);
                   2004:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2005: 	return -1;
                   2006:     }
1.599     albertel 2007:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2008: }
                   2009: 
1.1       albertel 2010: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2011: 
1.1       albertel 2012: sub subscribe {
                   2013:     my $fname=shift;
1.761     raeburn  2014:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2015:     $fname=~s/[\n\r]//g;
1.1       albertel 2016:     my $author=$fname;
                   2017:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2018:     my ($udom,$uname)=split(/\//,$author);
                   2019:     my $home=homeserver($uname,$udom);
1.335     albertel 2020:     if ($home eq 'no_host') {
                   2021:         return 'not_found';
1.1       albertel 2022:     }
                   2023:     my $answer=reply("sub:$fname",$home);
1.64      www      2024:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2025: 	$answer.=' by '.$home;
                   2026:     }
1.1       albertel 2027:     return $answer;
                   2028: }
                   2029:     
1.8       www      2030: # -------------------------------------------------------------- Replicate file
                   2031: 
                   2032: sub repcopy {
                   2033:     my $filename=shift;
1.23      www      2034:     $filename=~s/\/+/\//g;
1.607     raeburn  2035:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2036:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2037:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2038: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2039: 	return &repcopy_userfile($filename);
                   2040:     }
1.532     albertel 2041:     $filename=~s/[\n\r]//g;
1.8       www      2042:     my $transname="$filename.in.transfer";
1.828     www      2043: # FIXME: this should flock
1.607     raeburn  2044:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2045:     my $remoteurl=subscribe($filename);
1.64      www      2046:     if ($remoteurl =~ /^con_lost by/) {
                   2047: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2048:            return 'unavailable';
1.8       www      2049:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2050: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2051: 	   return 'not_found';
1.64      www      2052:     } elsif ($remoteurl =~ /^rejected by/) {
                   2053: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2054:            return 'forbidden';
1.20      www      2055:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2056:            return 'ok';
1.8       www      2057:     } else {
1.290     www      2058:         my $author=$filename;
                   2059:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2060:         my ($udom,$uname)=split(/\//,$author);
                   2061:         my $home=homeserver($uname,$udom);
                   2062:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2063:            my @parts=split(/\//,$filename);
                   2064:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2065:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2066:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2067: 	       return 'bad_request';
1.8       www      2068:            }
                   2069:            my $count;
                   2070:            for ($count=5;$count<$#parts;$count++) {
                   2071:                $path.="/$parts[$count]";
                   2072:                if ((-e $path)!=1) {
                   2073: 		   mkdir($path,0777);
                   2074:                }
                   2075:            }
                   2076:            my $ua=new LWP::UserAgent;
                   2077:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2078:            my $response=$ua->request($request,$transname);
                   2079:            if ($response->is_error()) {
                   2080: 	       unlink($transname);
                   2081:                my $message=$response->status_line;
1.672     albertel 2082:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2083:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2084:                return 'unavailable';
1.8       www      2085:            } else {
1.16      www      2086: 	       if ($remoteurl!~/\.meta$/) {
                   2087:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2088:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2089:                   if ($mresponse->is_error()) {
                   2090: 		      unlink($filename.'.meta');
                   2091:                       &logthis(
1.672     albertel 2092:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2093:                   }
                   2094: 	       }
1.8       www      2095:                rename($transname,$filename);
1.607     raeburn  2096:                return 'ok';
1.8       www      2097:            }
1.290     www      2098:        }
1.8       www      2099:     }
1.330     www      2100: }
                   2101: 
                   2102: # ------------------------------------------------ Get server side include body
                   2103: sub ssi_body {
1.381     albertel 2104:     my ($filelink,%form)=@_;
1.606     matthew  2105:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2106:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2107:     }
1.953     www      2108:     my $output='';
                   2109:     my $response;
1.980     raeburn  2110:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2111:        ($output,$response)=&externalssi($filelink);
1.953     www      2112:     } else {
1.1004    droeschl 2113:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2114:        $filelink .= 'inhibitmenu=yes';
1.953     www      2115:        ($output,$response)=&ssi($filelink,%form);
                   2116:     }
1.778     albertel 2117:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2118:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2119:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2120:     if (wantarray) {
                   2121:         return ($output, $response);
                   2122:     } else {
                   2123:         return $output;
                   2124:     }
1.8       www      2125: }
                   2126: 
1.15      www      2127: # --------------------------------------------------------- Server Side Include
                   2128: 
1.782     albertel 2129: sub absolute_url {
                   2130:     my ($host_name) = @_;
                   2131:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2132:     if ($host_name eq '') {
                   2133: 	$host_name = $ENV{'SERVER_NAME'};
                   2134:     }
                   2135:     return $protocol.$host_name;
                   2136: }
                   2137: 
1.942     foxr     2138: #
                   2139: #   Server side include.
                   2140: # Parameters:
                   2141: #  fn     Possibly encrypted resource name/id.
                   2142: #  form   Hash that describes how the rendering should be done
                   2143: #         and other things.
1.944     foxr     2144: # Returns:
1.950     raeburn  2145: #   Scalar context: The content of the response.
                   2146: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2147: #     
1.15      www      2148: sub ssi {
                   2149: 
1.944     foxr     2150:     my ($fn,%form)=@_;
1.15      www      2151:     my $ua=new LWP::UserAgent;
1.23      www      2152:     my $request;
1.711     albertel 2153: 
                   2154:     $form{'no_update_last_known'}=1;
1.895     albertel 2155:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2156:     if (%form) {
1.782     albertel 2157:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2158:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2159:     } else {
1.782     albertel 2160:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2161:     }
                   2162: 
1.15      www      2163:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2164:     my $response=$ua->request($request);
                   2165: 
1.944     foxr     2166:     if (wantarray) {
                   2167: 	return ($response->content, $response);
                   2168:     } else {
                   2169: 	return $response->content;
1.942     foxr     2170:     }
1.324     www      2171: }
                   2172: 
                   2173: sub externalssi {
                   2174:     my ($url)=@_;
                   2175:     my $ua=new LWP::UserAgent;
                   2176:     my $request=new HTTP::Request('GET',$url);
                   2177:     my $response=$ua->request($request);
1.954     raeburn  2178:     if (wantarray) {
                   2179:         return ($response->content, $response);
                   2180:     } else {
                   2181:         return $response->content;
                   2182:     }
1.15      www      2183: }
1.254     www      2184: 
1.492     albertel 2185: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2186: 
                   2187: sub allowuploaded {
                   2188:     my ($srcurl,$url)=@_;
                   2189:     $url=&clutter(&declutter($url));
                   2190:     my $dir=$url;
                   2191:     $dir=~s/\/[^\/]+$//;
                   2192:     my %httpref=();
                   2193:     my $httpurl=&hreflocation('',$url);
                   2194:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2195:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2196: }
1.477     raeburn  2197: 
1.478     albertel 2198: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2199: # input: action, courseID, current domain, intended
1.637     raeburn  2200: #        path to file, source of file, instruction to parse file for objects,
                   2201: #        ref to hash for embedded objects,
                   2202: #        ref to hash for codebase of java objects.
                   2203: #
1.485     raeburn  2204: # output: url to file (if action was uploaddoc), 
                   2205: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2206: #
1.478     albertel 2207: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2208: # course.
1.477     raeburn  2209: #
1.478     albertel 2210: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2211: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2212: #          course's home server.
1.477     raeburn  2213: #
1.478     albertel 2214: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2215: #          be copied from $source (current location) to 
                   2216: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2217: #         and will then be copied to
                   2218: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2219: #         course's home server.
1.485     raeburn  2220: #
1.481     raeburn  2221: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2222: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2223: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2224: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2225: #         in course's home server.
1.637     raeburn  2226: #
1.477     raeburn  2227: 
                   2228: sub process_coursefile {
1.638     albertel 2229:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2230:     my $fetchresult;
1.638     albertel 2231:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2232:     if ($action eq 'propagate') {
1.638     albertel 2233:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2234: 			     $home);
1.481     raeburn  2235:     } else {
1.477     raeburn  2236:         my $fpath = '';
                   2237:         my $fname = $file;
1.478     albertel 2238:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2239:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2240:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2241:         if ($action eq 'copy') {
                   2242:             if ($source eq '') {
                   2243:                 $fetchresult = 'no source file';
                   2244:                 return $fetchresult;
                   2245:             } else {
                   2246:                 my $destination = $filepath.'/'.$fname;
                   2247:                 rename($source,$destination);
                   2248:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2249:                                  $home);
1.481     raeburn  2250:             }
                   2251:         } elsif ($action eq 'uploaddoc') {
                   2252:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2253:             print $fh $env{'form.'.$source};
1.481     raeburn  2254:             close($fh);
1.637     raeburn  2255:             if ($parser eq 'parse') {
1.1024    raeburn  2256:                 my $mm = new File::MMagic;
                   2257:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2258:                 if ($mime_type eq 'text/html') {
                   2259:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2260:                     unless ($parse_result eq 'ok') {
                   2261:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2262:                     }
1.637     raeburn  2263:                 }
                   2264:             }
1.477     raeburn  2265:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2266:                                  $home);
1.481     raeburn  2267:             if ($fetchresult eq 'ok') {
                   2268:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2269:             } else {
                   2270:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2271:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2272:                 return '/adm/notfound.html';
                   2273:             }
1.477     raeburn  2274:         }
                   2275:     }
1.485     raeburn  2276:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2277:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2278:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2279:     }
                   2280:     return $fetchresult;
                   2281: }
                   2282: 
1.637     raeburn  2283: sub build_filepath {
                   2284:     my ($fpath) = @_;
                   2285:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2286:     unless ($fpath eq '') {
                   2287:         my @parts=split('/',$fpath);
                   2288:         foreach my $part (@parts) {
                   2289:             $filepath.= '/'.$part;
                   2290:             if ((-e $filepath)!=1) {
                   2291:                 mkdir($filepath,0777);
                   2292:             }
                   2293:         }
                   2294:     }
                   2295:     return $filepath;
                   2296: }
                   2297: 
                   2298: sub store_edited_file {
1.638     albertel 2299:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2300:     my $file = $primary_url;
                   2301:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2302:     my $fpath = '';
                   2303:     my $fname = $file;
                   2304:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2305:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2306:     my $filepath = &build_filepath($fpath);
                   2307:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2308:     print $fh $content;
                   2309:     close($fh);
1.638     albertel 2310:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2311:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2312: 			  $home);
1.637     raeburn  2313:     if ($$fetchresult eq 'ok') {
                   2314:         return '/uploaded/'.$fpath.'/'.$fname;
                   2315:     } else {
1.638     albertel 2316:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2317: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2318:         return '/adm/notfound.html';
                   2319:     }
                   2320: }
                   2321: 
1.531     albertel 2322: sub clean_filename {
1.831     albertel 2323:     my ($fname,$args)=@_;
1.315     www      2324: # Replace Windows backslashes by forward slashes
1.257     www      2325:     $fname=~s/\\/\//g;
1.831     albertel 2326:     if (!$args->{'keep_path'}) {
                   2327:         # Get rid of everything but the actual filename
                   2328: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2329:     }
1.315     www      2330: # Replace spaces by underscores
                   2331:     $fname=~s/\s+/\_/g;
                   2332: # Replace all other weird characters by nothing
1.831     albertel 2333:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2334: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2335: # numbers
                   2336:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2337:     return $fname;
                   2338: }
1.1051    raeburn  2339: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2340: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2341: # image with the same aspect ratio as the original, but with dimensions which do 
                   2342: # not exceed $resizewidth and $resizeheight.
                   2343:  
1.984     neumanie 2344: sub resizeImage {
1.1051    raeburn  2345:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2346:     my $ima = Image::Magick->new;
                   2347:     my $resized;
                   2348:     if (-e $img_path) {
                   2349:         $ima->Read($img_path);
                   2350:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2351:             my $width = $ima->Get('width');
                   2352:             my $height = $ima->Get('height');
                   2353:             if ($width > $resizewidth) {
                   2354: 	        my $factor = $width/$resizewidth;
                   2355:                 my $newheight = $height/$factor;
                   2356:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2357:                 $resized = 1;
                   2358:             }
                   2359:         }
                   2360:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2361:             my $width = $ima->Get('width');
                   2362:             my $height = $ima->Get('height');
                   2363:             if ($height > $resizeheight) {
                   2364:                 my $factor = $height/$resizeheight;
                   2365:                 my $newwidth = $width/$factor;
                   2366:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2367:                 $resized = 1;
                   2368:             }
                   2369:         }
                   2370:         if ($resized) {
                   2371:             $ima->Write($img_path);
                   2372:         }
                   2373:     }
                   2374:     return;
1.977     amueller 2375: }
                   2376: 
1.608     albertel 2377: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2378: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2379: #                    the desired filename is in $env{"form.$formname.filename"}
                   2380: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2381: #                                    canceloverwrite, or ''.
                   2382: #                   if 'coursedoc': upload to the current course
                   2383: #                   if 'existingfile': write file to tmp/overwrites directory
                   2384: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2385: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2386: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2387: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2388: #        $allfiles - reference to hash for embedded objects
                   2389: #        $codebase - reference to hash for codebase of java objects
                   2390: #        $desuname - username for permanent storage of uploaded file
                   2391: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2392: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2393: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2394: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2395: #        $resizeheight - height (pixels) to which to resize uploaded image
1.858     raeburn  2396: # 
1.686     albertel 2397: # output: url of file in userspace, or error: <message> 
                   2398: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2399: 
1.531     albertel 2400: sub userfileupload {
1.1056.4.13  raeburn  2401:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051    raeburn  2402:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531     albertel 2403:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2404:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2405:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2406:     # See if there is anything left
1.257     www      2407:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2408:     chop($env{'form.'.$formname});
1.1056.4.13  raeburn  2409:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2410:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2411:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2412:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2413:         my $now = time;
1.1056.4.13  raeburn  2414:         my $filepath;
                   2415:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2416:              $filepath = 'tmp/helprequests/'.$now;
                   2417:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2418:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2419:                          '_'.$env{'user.domain'}.'/pending';
                   2420:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2421:             my ($docuname,$docudom);
                   2422:             if ($destudom) {
                   2423:                 $docudom = $destudom;
                   2424:             } else {
                   2425:                 $docudom = $env{'user.domain'};
                   2426:             }
                   2427:             if ($destuname) {
                   2428:                 $docuname = $destuname;
                   2429:             } else {
                   2430:                 $docuname = $env{'user.name'};
                   2431:             }
                   2432:             if (exists($env{'form.group'})) {
                   2433:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2434:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2435:             }
                   2436:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2437:             if ($context eq 'canceloverwrite') {
                   2438:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2439:                 if (-e  $tempfile) {
                   2440:                     my @info = stat($tempfile);
                   2441:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2442:                         unlink($tempfile);
                   2443:                     }
                   2444:                 }
                   2445:                 return;
1.523     raeburn  2446:             }
                   2447:         }
1.1056.4.13  raeburn  2448:         # Create the directory if not present
1.741     raeburn  2449:         my @parts=split(/\//,$filepath);
                   2450:         my $fullpath = $perlvar{'lonDaemons'};
                   2451:         for (my $i=0;$i<@parts;$i++) {
                   2452:             $fullpath .= '/'.$parts[$i];
                   2453:             if ((-e $fullpath)!=1) {
                   2454:                 mkdir($fullpath,0777);
                   2455:             }
                   2456:         }
                   2457:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2458:         print $fh $env{'form.'.$formname};
                   2459:         close($fh);
1.1056.4.13  raeburn  2460:         if ($context eq 'existingfile') {
                   2461:             my @info = stat($fullpath.'/'.$fname);
                   2462:             return ($fullpath.'/'.$fname,$info[9]);
                   2463:         } else {
                   2464:             return $fullpath.'/'.$fname;
                   2465:         }
1.523     raeburn  2466:     }
1.995     raeburn  2467:     if ($subdir eq 'scantron') {
                   2468:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14! raeburn  2469:     } else {
1.995     raeburn  2470:         $fname="$subdir/$fname";
                   2471:     }
1.1056.4.13  raeburn  2472:     if ($context eq 'coursedoc') {
1.638     albertel 2473: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2474: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2475:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2476:             return &finishuserfileupload($docuname,$docudom,
                   2477: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2478: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.13  raeburn  2479:                                          $resizewidth,$resizeheight,$context);
1.481     raeburn  2480:         } else {
1.620     albertel 2481:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2482:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2483: 				       $fname,$formname,$parser,
                   2484: 				       $allfiles,$codebase);
1.481     raeburn  2485:         }
1.719     banghart 2486:     } elsif (defined($destuname)) {
                   2487:         my $docuname=$destuname;
                   2488:         my $docudom=$destudom;
1.860     raeburn  2489: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2490: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2491:                                      $thumbwidth,$thumbheight,
1.1056.4.13  raeburn  2492:                                      $resizewidth,$resizeheight,$context);
1.259     www      2493:     } else {
1.638     albertel 2494:         my $docuname=$env{'user.name'};
                   2495:         my $docudom=$env{'user.domain'};
1.714     raeburn  2496:         if (exists($env{'form.group'})) {
                   2497:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2498:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2499:         }
1.860     raeburn  2500: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2501: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2502:                                      $thumbwidth,$thumbheight,
1.1056.4.13  raeburn  2503:                                      $resizewidth,$resizeheight,$context);
1.259     www      2504:     }
1.271     www      2505: }
                   2506: 
                   2507: sub finishuserfileupload {
1.860     raeburn  2508:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.13  raeburn  2509:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context) = @_;
1.477     raeburn  2510:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2511:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2512:   
1.860     raeburn  2513:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2514:     $file=$fname;
                   2515:     if ($fname=~m|/|) {
                   2516:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2517: 	$path.=$fnamepath.'/';
                   2518:     }
1.259     www      2519:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2520:     my $count;
                   2521:     for ($count=4;$count<=$#parts;$count++) {
                   2522:         $filepath.="/$parts[$count]";
                   2523:         if ((-e $filepath)!=1) {
                   2524: 	    mkdir($filepath,0777);
                   2525:         }
                   2526:     }
1.984     neumanie 2527: 
1.258     www      2528: # Save the file
                   2529:     {
1.701     albertel 2530: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2531: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2532: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2533: 	    return '/adm/notfound.html';
                   2534: 	}
1.1056.4.13  raeburn  2535:         if ($context eq 'overwrite') {
                   2536:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2537:             my $target = $filepath.'/'.$file;
                   2538:             if (-e $source) {
                   2539:                 my @info = stat($source);
                   2540:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2541:                     unless (&File::Copy::move($source,$target)) {
                   2542:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2543:                         return "Moving from $source failed";
                   2544:                     }
                   2545:                 } else {
                   2546:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2547:                 }
                   2548:             } else {
                   2549:                 return "Temporary file: $source missing";
                   2550:             }
                   2551: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2552: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2553: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2554: 	    return '/adm/notfound.html';
                   2555: 	}
1.570     albertel 2556: 	close(FH);
1.1051    raeburn  2557:         if ($resizewidth && $resizeheight) {
                   2558:             my $mm = new File::MMagic;
                   2559:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2560:             if ($mime_type =~ m{^image/}) {
                   2561: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2562:             }  
1.977     amueller 2563: 	}
1.258     www      2564:     }
1.637     raeburn  2565:     if ($parser eq 'parse') {
1.1024    raeburn  2566:         my $mm = new File::MMagic;
                   2567:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2568:         if ($mime_type eq 'text/html') {
                   2569:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2570:                                                        $allfiles,$codebase);
                   2571:             unless ($parse_result eq 'ok') {
                   2572:                 &logthis('Failed to parse '.$filepath.$file.
                   2573: 	   	         ' for embedded media: '.$parse_result); 
                   2574:             }
1.637     raeburn  2575:         }
                   2576:     }
1.860     raeburn  2577:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2578:         my $input = $filepath.'/'.$file;
                   2579:         my $output = $filepath.'/'.'tn-'.$file;
                   2580:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2581:         system("convert -sample $thumbsize $input $output");
                   2582:         if (-e $filepath.'/'.'tn-'.$file) {
                   2583:             $fetchthumb  = 1; 
                   2584:         }
                   2585:     }
1.858     raeburn  2586:  
1.259     www      2587: # Notify homeserver to grep it
                   2588: #
1.984     neumanie 2589:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2590:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2591:     if ($fetchresult eq 'ok') {
1.860     raeburn  2592:         if ($fetchthumb) {
                   2593:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2594:             if ($thumbresult ne 'ok') {
                   2595:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2596:                          $docuhome.': '.$thumbresult);
                   2597:             }
                   2598:         }
1.259     www      2599: #
1.258     www      2600: # Return the URL to it
1.494     albertel 2601:         return '/uploaded/'.$path.$file;
1.263     www      2602:     } else {
1.494     albertel 2603:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2604: 		 ': '.$fetchresult);
1.263     www      2605:         return '/adm/notfound.html';
1.858     raeburn  2606:     }
1.493     albertel 2607: }
                   2608: 
1.637     raeburn  2609: sub extract_embedded_items {
1.961     raeburn  2610:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2611:     my @state = ();
                   2612:     my %javafiles = (
                   2613:                       codebase => '',
                   2614:                       code => '',
                   2615:                       archive => ''
                   2616:                     );
                   2617:     my %mediafiles = (
                   2618:                       src => '',
                   2619:                       movie => '',
                   2620:                      );
1.648     raeburn  2621:     my $p;
                   2622:     if ($content) {
                   2623:         $p = HTML::LCParser->new($content);
                   2624:     } else {
1.961     raeburn  2625:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2626:     }
1.641     albertel 2627:     while (my $t=$p->get_token()) {
1.640     albertel 2628: 	if ($t->[0] eq 'S') {
                   2629: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2630: 	    push(@state, $tagname);
1.648     raeburn  2631:             if (lc($tagname) eq 'allow') {
                   2632:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2633:             }
1.640     albertel 2634: 	    if (lc($tagname) eq 'img') {
                   2635: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2636: 	    }
1.886     albertel 2637: 	    if (lc($tagname) eq 'a') {
                   2638: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2639: 	    }
1.645     raeburn  2640:             if (lc($tagname) eq 'script') {
                   2641:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2642:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2643:                 } else {
                   2644:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2645:                 }
                   2646:             }
                   2647:             if (lc($tagname) eq 'link') {
                   2648:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2649:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2650:                 }
                   2651:             }
1.640     albertel 2652: 	    if (lc($tagname) eq 'object' ||
                   2653: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2654: 		foreach my $item (keys(%javafiles)) {
                   2655: 		    $javafiles{$item} = '';
                   2656: 		}
                   2657: 	    }
                   2658: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2659: 		my $name = lc($attr->{'name'});
                   2660: 		foreach my $item (keys(%javafiles)) {
                   2661: 		    if ($name eq $item) {
                   2662: 			$javafiles{$item} = $attr->{'value'};
                   2663: 			last;
                   2664: 		    }
                   2665: 		}
                   2666: 		foreach my $item (keys(%mediafiles)) {
                   2667: 		    if ($name eq $item) {
                   2668: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2669: 			last;
                   2670: 		    }
                   2671: 		}
                   2672: 	    }
                   2673: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2674: 		foreach my $item (keys(%javafiles)) {
                   2675: 		    if ($attr->{$item}) {
                   2676: 			$javafiles{$item} = $attr->{$item};
                   2677: 			last;
                   2678: 		    }
                   2679: 		}
                   2680: 		foreach my $item (keys(%mediafiles)) {
                   2681: 		    if ($attr->{$item}) {
                   2682: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2683: 			last;
                   2684: 		    }
                   2685: 		}
                   2686: 	    }
                   2687: 	} elsif ($t->[0] eq 'E') {
                   2688: 	    my ($tagname) = ($t->[1]);
                   2689: 	    if ($javafiles{'codebase'} ne '') {
                   2690: 		$javafiles{'codebase'} .= '/';
                   2691: 	    }  
                   2692: 	    if (lc($tagname) eq 'applet' ||
                   2693: 		lc($tagname) eq 'object' ||
                   2694: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2695: 		) {
                   2696: 		foreach my $item (keys(%javafiles)) {
                   2697: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2698: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2699: 			&add_filetype($allfiles,$file,$item);
                   2700: 		    }
                   2701: 		}
                   2702: 	    } 
                   2703: 	    pop @state;
                   2704: 	}
                   2705:     }
1.637     raeburn  2706:     return 'ok';
                   2707: }
                   2708: 
1.639     albertel 2709: sub add_filetype {
                   2710:     my ($allfiles,$file,$type)=@_;
                   2711:     if (exists($allfiles->{$file})) {
                   2712: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2713: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2714: 	}
                   2715:     } else {
                   2716: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2717:     }
                   2718: }
                   2719: 
1.493     albertel 2720: sub removeuploadedurl {
1.984     neumanie 2721:     my ($url)=@_;	
                   2722:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2723:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2724: }
                   2725: 
                   2726: sub removeuserfile {
                   2727:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2728:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2729:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2730:     if ($result eq 'ok') {	
1.798     raeburn  2731:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2732:             my $metafile = $fname.'.meta';
                   2733:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2734: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2735:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2736:             my $sqlresult = 
1.823     albertel 2737:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2738:                                         'portfolio_metadata',$group,
                   2739:                                         'delete');
1.798     raeburn  2740:         }
                   2741:     }
                   2742:     return $result;
1.257     www      2743: }
1.15      www      2744: 
1.530     albertel 2745: sub mkdiruserfile {
                   2746:     my ($docuname,$docudom,$dir)=@_;
                   2747:     my $home=&homeserver($docuname,$docudom);
                   2748:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2749: }
                   2750: 
1.531     albertel 2751: sub renameuserfile {
                   2752:     my ($docuname,$docudom,$old,$new)=@_;
                   2753:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2754:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2755:                         &escape("$old").':'.&escape("$new"),$home);
                   2756:     if ($result eq 'ok') {
                   2757:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2758:             my $oldmeta = $old.'.meta';
                   2759:             my $newmeta = $new.'.meta';
                   2760:             my $metaresult = 
                   2761:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2762: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2763:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2764:             my $sqlresult = 
1.823     albertel 2765:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2766:                                         'portfolio_metadata',$group,
                   2767:                                         'delete');
1.798     raeburn  2768:         }
                   2769:     }
                   2770:     return $result;
1.531     albertel 2771: }
                   2772: 
1.14      www      2773: # ------------------------------------------------------------------------- Log
                   2774: 
                   2775: sub log {
                   2776:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2777:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2778: }
                   2779: 
                   2780: # ------------------------------------------------------------------ Course Log
1.352     www      2781: #
                   2782: # This routine flushes several buffers of non-mission-critical nature
                   2783: #
1.157     www      2784: 
                   2785: sub flushcourselogs {
1.352     www      2786:     &logthis('Flushing log buffers');
                   2787: #
                   2788: # course logs
                   2789: # This is a log of all transactions in a course, which can be used
                   2790: # for data mining purposes
                   2791: #
                   2792: # It also collects the courseid database, which lists last transaction
                   2793: # times and course titles for all courseids
                   2794: #
                   2795:     my %courseidbuffer=();
1.921     raeburn  2796:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2797:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2798: 		          &escape($courselogs{$crsid}),
                   2799: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2800: 	    delete $courselogs{$crsid};
                   2801:         } else {
                   2802:             &logthis('Failed to flush log buffer for '.$crsid);
                   2803:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2804:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2805:                         " exceeded maximum size, deleting.</font>");
                   2806:                delete $courselogs{$crsid};
                   2807:             }
1.352     www      2808:         }
1.920     raeburn  2809:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2810:             'description' => $coursedescrbuf{$crsid},
                   2811:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2812:             'type'        => $coursetypebuf{$crsid},
                   2813:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2814:         };
1.191     harris41 2815:     }
1.352     www      2816: #
                   2817: # Write course id database (reverse lookup) to homeserver of courses 
                   2818: # Is used in pickcourse
                   2819: #
1.840     albertel 2820:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2821:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2822:                                     $courseidbuffer{$crs_home},
                   2823:                                     $crs_home,'timeonly');
1.352     www      2824:     }
                   2825: #
                   2826: # File accesses
                   2827: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2828: #
1.449     matthew  2829:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2830:         if ($entry =~ /___count$/) {
                   2831:             my ($dom,$name);
1.807     albertel 2832:             ($dom,$name,undef)=
1.811     albertel 2833: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2834:             if (! defined($dom) || $dom eq '' || 
                   2835:                 ! defined($name) || $name eq '') {
1.620     albertel 2836:                 my $cid = $env{'request.course.id'};
                   2837:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2838:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2839:             }
1.450     matthew  2840:             my $value = $accesshash{$entry};
                   2841:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2842:             my %temphash=($url => $value);
1.449     matthew  2843:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2844:             if ($result eq 'ok') {
                   2845:                 delete $accesshash{$entry};
                   2846:             } elsif ($result eq 'unknown_cmd') {
                   2847:                 # Target server has old code running on it.
1.450     matthew  2848:                 my %temphash=($entry => $value);
1.449     matthew  2849:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2850:                     delete $accesshash{$entry};
                   2851:                 }
                   2852:             }
                   2853:         } else {
1.811     albertel 2854:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2855:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2856:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2857:                 delete $accesshash{$entry};
                   2858:             }
1.185     www      2859:         }
1.191     harris41 2860:     }
1.352     www      2861: #
                   2862: # Roles
                   2863: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2864: #
1.800     albertel 2865:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2866:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2867: 	    split(/\:/,$entry);
                   2868:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2869:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2870:                 $rudom,$runame) eq 'ok') {
                   2871: 	    delete $userrolehash{$entry};
                   2872:         }
                   2873:     }
1.662     raeburn  2874: #
                   2875: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2876: #
                   2877:     my %domrolebuffer = ();
1.1000    raeburn  2878:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2879:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2880:         if ($domrolebuffer{$rudom}) {
                   2881:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2882:                       '='.&escape($domainrolehash{$entry});
                   2883:         } else {
                   2884:             $domrolebuffer{$rudom}.=&escape($entry).
                   2885:                       '='.&escape($domainrolehash{$entry});
                   2886:         }
                   2887:         delete $domainrolehash{$entry};
                   2888:     }
                   2889:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2890: 	my %servers = &get_servers($dom,'library');
                   2891: 	foreach my $tryserver (keys(%servers)) {
                   2892: 	    unless (&reply('domroleput:'.$dom.':'.
                   2893: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2894: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2895: 	    }
1.662     raeburn  2896:         }
                   2897:     }
1.186     www      2898:     $dumpcount++;
1.157     www      2899: }
                   2900: 
                   2901: sub courselog {
                   2902:     my $what=shift;
1.158     www      2903:     $what=time.':'.$what;
1.620     albertel 2904:     unless ($env{'request.course.id'}) { return ''; }
                   2905:     $coursedombuf{$env{'request.course.id'}}=
                   2906:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2907:     $coursenumbuf{$env{'request.course.id'}}=
                   2908:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2909:     $coursehombuf{$env{'request.course.id'}}=
                   2910:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2911:     $coursedescrbuf{$env{'request.course.id'}}=
                   2912:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2913:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2914:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2915:     $courseownerbuf{$env{'request.course.id'}}=
                   2916:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2917:     $coursetypebuf{$env{'request.course.id'}}=
                   2918:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2919:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2920: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2921:     } else {
1.620     albertel 2922: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2923:     }
1.620     albertel 2924:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2925: 	&flushcourselogs();
                   2926:     }
1.158     www      2927: }
                   2928: 
                   2929: sub courseacclog {
                   2930:     my $fnsymb=shift;
1.620     albertel 2931:     unless ($env{'request.course.id'}) { return ''; }
                   2932:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2933:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2934:         $what.=':POST';
1.583     matthew  2935:         # FIXME: Probably ought to escape things....
1.800     albertel 2936: 	foreach my $key (keys(%env)) {
                   2937:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2938:                 my $formitem = $1;
                   2939:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2940:                     $what.=':'.$formitem.'='.$env{$key};
                   2941:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2942:                     $what.=':'.$formitem.'='.$env{$key};
                   2943:                 }
1.158     www      2944:             }
1.191     harris41 2945:         }
1.583     matthew  2946:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2947:         # FIXME: We should not be depending on a form parameter that someone
                   2948:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2949:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2950:             $what.= ':POST';
                   2951:             # FIXME: Probably ought to escape things....
                   2952:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2953:                                  'crsdiscuss') {
1.620     albertel 2954:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2955:             }
                   2956:         }
1.158     www      2957:     }
                   2958:     &courselog($what);
1.149     www      2959: }
                   2960: 
1.185     www      2961: sub countacc {
                   2962:     my $url=&declutter(shift);
1.458     matthew  2963:     return if (! defined($url) || $url eq '');
1.620     albertel 2964:     unless ($env{'request.course.id'}) { return ''; }
                   2965:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2966:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2967:     $accesshash{$key}++;
1.185     www      2968: }
1.349     www      2969: 
1.361     www      2970: sub linklog {
                   2971:     my ($from,$to)=@_;
                   2972:     $from=&declutter($from);
                   2973:     $to=&declutter($to);
                   2974:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2975:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2976: }
                   2977:   
1.349     www      2978: sub userrolelog {
                   2979:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2980:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2981:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2982:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2983:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2984:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2985:        $userrolehash
                   2986:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2987:                     =$tend.':'.$tstart;
1.662     raeburn  2988:     }
1.898     albertel 2989:     if (($env{'request.role'} =~ /dc\./) &&
                   2990: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2991: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2992: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2993:          ($trole=~/^co/))) {
1.898     albertel 2994:        $userrolehash
                   2995:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2996:                     =$tend.':'.$tstart;
                   2997:     }
1.662     raeburn  2998:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2999:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3000:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3001:         ($trole=~/^sc/)) {
                   3002:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3003:        $domainrolehash
                   3004:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3005:                     = $tend.':'.$tstart;
                   3006:     }
1.351     www      3007: }
                   3008: 
1.957     raeburn  3009: sub courserolelog {
                   3010:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3011:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3012:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3013:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3014:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3015:         ($trole eq 'co')) {
1.957     raeburn  3016:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3017:             my $cdom = $1;
                   3018:             my $cnum = $2;
                   3019:             my $sec = $3;
                   3020:             my $namespace = 'rolelog';
                   3021:             my %storehash = (
                   3022:                                role    => $trole,
                   3023:                                start   => $tstart,
                   3024:                                end     => $tend,
                   3025:                                selfenroll => $selfenroll,
                   3026:                                context    => $context,
                   3027:                             );
                   3028:             if ($trole eq 'gr') {
                   3029:                 $namespace = 'groupslog';
                   3030:                 $storehash{'group'} = $sec;
                   3031:             } else {
                   3032:                 $storehash{'section'} = $sec;
                   3033:             }
                   3034:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3035:             if (($trole ne 'st') || ($sec ne '')) {
                   3036:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3037:             }
1.957     raeburn  3038:         }
                   3039:     }
                   3040:     return;
                   3041: }
                   3042: 
1.351     www      3043: sub get_course_adv_roles {
1.948     raeburn  3044:     my ($cid,$codes) = @_;
1.620     albertel 3045:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3046:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3047:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3048:     my %nothide=();
1.800     albertel 3049:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3050:         if ($user !~ /:/) {
                   3051: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3052:         } else {
                   3053:             $nothide{$user}=1;
                   3054:         }
1.470     www      3055:     }
1.351     www      3056:     my %returnhash=();
                   3057:     my %dumphash=
                   3058:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3059:     my $now=time;
1.997     raeburn  3060:     my %privileged;
1.1000    raeburn  3061:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3062: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3063:         if (($tstart) && ($tstart<0)) { next; }
                   3064:         if (($tend) && ($tend<$now)) { next; }
                   3065:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3066:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3067: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3068:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3069:             my %dompersonnel =
1.998     raeburn  3070:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3071:             $privileged{$domain} = {};
                   3072:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3073:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3074:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3075:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3076:                         $privileged{$udom}{$uname} = 1;
                   3077:                     }
                   3078:                 }
                   3079:             }
                   3080:         }
                   3081:         if ((exists($privileged{$domain}{$username})) && 
                   3082:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3083: 	if ($role eq 'cr') { next; }
1.948     raeburn  3084:         if ($codes) {
                   3085:             if ($section) { $role .= ':'.$section; }
                   3086:             if ($returnhash{$role}) {
                   3087:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3088:             } else {
                   3089:                 $returnhash{$role}=$username.':'.$domain;
                   3090:             }
1.351     www      3091:         } else {
1.988     raeburn  3092:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3093:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3094:             if ($returnhash{$key}) {
                   3095: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3096:             } else {
                   3097:                 $returnhash{$key}=$username.':'.$domain;
                   3098:             }
1.351     www      3099:         }
1.948     raeburn  3100:     }
1.400     www      3101:     return %returnhash;
                   3102: }
                   3103: 
                   3104: sub get_my_roles {
1.937     raeburn  3105:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3106:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3107:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3108:     my (%dumphash,%nothide);
1.858     raeburn  3109:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3110:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3111:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3112:     } else {
                   3113:         %dumphash=
1.400     www      3114:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3115:         if ($hidepriv) {
                   3116:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3117:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3118:                 if ($user !~ /:/) {
                   3119:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3120:                 } else {
                   3121:                     $nothide{$user} = 1;
                   3122:                 }
                   3123:             }
                   3124:         }
1.858     raeburn  3125:     }
1.400     www      3126:     my %returnhash=();
                   3127:     my $now=time;
1.999     raeburn  3128:     my %privileged;
1.800     albertel 3129:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3130:         my ($role,$tend,$tstart);
                   3131:         if ($context eq 'userroles') {
                   3132: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3133:         } else {
                   3134:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3135:         }
1.400     www      3136:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3137:         my $status = 'active';
1.939     raeburn  3138:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3139:             $status = 'previous';
                   3140:         } 
                   3141:         if (($tstart) && ($now<$tstart)) {
                   3142:             $status = 'future';
                   3143:         }
                   3144:         if (ref($types) eq 'ARRAY') {
                   3145:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3146:                 next;
                   3147:             } 
                   3148:         } else {
                   3149:             if ($status ne 'active') {
                   3150:                 next;
                   3151:             }
                   3152:         }
1.867     raeburn  3153:         my ($rolecode,$username,$domain,$section,$area);
                   3154:         if ($context eq 'userroles') {
                   3155:             ($area,$rolecode) = split(/_/,$entry);
                   3156:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3157:         } else {
                   3158:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3159:         }
1.832     raeburn  3160:         if (ref($roledoms) eq 'ARRAY') {
                   3161:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3162:                 next;
                   3163:             }
                   3164:         }
                   3165:         if (ref($roles) eq 'ARRAY') {
                   3166:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3167:                 if ($role =~ /^cr\//) {
                   3168:                     if (!grep(/^cr$/,@{$roles})) {
                   3169:                         next;
                   3170:                     }
                   3171:                 } else {
                   3172:                     next;
                   3173:                 }
1.832     raeburn  3174:             }
1.867     raeburn  3175:         }
1.937     raeburn  3176:         if ($hidepriv) {
1.999     raeburn  3177:             if ($context eq 'userroles') {
                   3178:                 if ((&privileged($username,$domain)) &&
                   3179:                     (!$nothide{$username.':'.$domain})) {
                   3180:                     next;
                   3181:                 }
                   3182:             } else {
                   3183:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3184:                     my %dompersonnel =
                   3185:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3186:                     $privileged{$domain} = {};
                   3187:                     if (keys(%dompersonnel)) {
                   3188:                         foreach my $server (keys(%dompersonnel)) {
                   3189:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3190:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3191:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3192:                                     $privileged{$udom}{$uname} = $trole;
                   3193:                                 }
                   3194:                             }
                   3195:                         }
                   3196:                     }
                   3197:                 }
                   3198:                 if (exists($privileged{$domain}{$username})) {
                   3199:                     if (!$nothide{$username.':'.$domain}) {
                   3200:                         next;
                   3201:                     }
                   3202:                 }
1.937     raeburn  3203:             }
                   3204:         }
1.933     raeburn  3205:         if ($withsec) {
                   3206:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3207:                 $tstart.':'.$tend;
                   3208:         } else {
                   3209:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3210:         }
1.832     raeburn  3211:     }
1.373     www      3212:     return %returnhash;
1.399     www      3213: }
                   3214: 
                   3215: # ----------------------------------------------------- Frontpage Announcements
                   3216: #
                   3217: #
                   3218: 
                   3219: sub postannounce {
                   3220:     my ($server,$text)=@_;
1.844     albertel 3221:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3222:     unless ($text=~/\w/) { $text=''; }
                   3223:     return &reply('setannounce:'.&escape($text),$server);
                   3224: }
                   3225: 
                   3226: sub getannounce {
1.448     albertel 3227: 
                   3228:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3229: 	my $announcement='';
1.800     albertel 3230: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3231: 	close($fh);
1.399     www      3232: 	if ($announcement=~/\w/) { 
                   3233: 	    return 
                   3234:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3235:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3236: 	} else {
                   3237: 	    return '';
                   3238: 	}
                   3239:     } else {
                   3240: 	return '';
                   3241:     }
1.351     www      3242: }
1.353     www      3243: 
                   3244: # ---------------------------------------------------------- Course ID routines
                   3245: # Deal with domain's nohist_courseid.db files
                   3246: #
                   3247: 
                   3248: sub courseidput {
1.921     raeburn  3249:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3250:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3251:     my $outcome;
                   3252:     if ($caller eq 'timeonly') {
                   3253:         my $cids = '';
                   3254:         foreach my $item (keys(%$storehash)) {
                   3255:             $cids.=&escape($item).'&';
                   3256:         }
                   3257:         $cids=~s/\&$//;
                   3258:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3259:                           $coursehome);       
                   3260:     } else {
                   3261:         my $items = '';
                   3262:         foreach my $item (keys(%$storehash)) {
                   3263:             $items.= &escape($item).'='.
                   3264:                      &freeze_escape($$storehash{$item}).'&';
                   3265:         }
                   3266:         $items=~s/\&$//;
                   3267:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3268:                           $coursehome);
1.918     raeburn  3269:     }
                   3270:     if ($outcome eq 'unknown_cmd') {
                   3271:         my $what;
                   3272:         foreach my $cid (keys(%$storehash)) {
                   3273:             $what .= &escape($cid).'=';
1.921     raeburn  3274:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3275:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3276:             }
                   3277:             $what =~ s/\:$/&/;
                   3278:         }
                   3279:         $what =~ s/\&$//;  
                   3280:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3281:     } else {
                   3282:         return $outcome;
                   3283:     }
1.353     www      3284: }
                   3285: 
                   3286: sub courseiddump {
1.921     raeburn  3287:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3288:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3289:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3290:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3291:     my $as_hash = 1;
                   3292:     my %returnhash;
                   3293:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3294:     my %libserv = &all_library();
                   3295:     foreach my $tryserver (keys(%libserv)) {
                   3296:         if ( (  $hostidflag == 1 
                   3297: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3298: 	     || (!defined($hostidflag)) ) {
                   3299: 
1.918     raeburn  3300: 	    if (($domfilter eq '') ||
                   3301: 		(&host_domain($tryserver) eq $domfilter)) {
                   3302:                 my $rep = 
                   3303:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3304:                          $sincefilter.':'.&escape($descfilter).':'.
                   3305:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3306:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3307:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3308:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3309:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3310:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3311:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3312:                          &escape($creationcontext).':'.$domcloner,
                   3313:                          $tryserver);
1.918     raeburn  3314:                 my @pairs=split(/\&/,$rep);
                   3315:                 foreach my $item (@pairs) {
                   3316:                     my ($key,$value)=split(/\=/,$item,2);
                   3317:                     $key = &unescape($key);
                   3318:                     next if ($key =~ /^error: 2 /);
                   3319:                     my $result = &thaw_unescape($value);
                   3320:                     if (ref($result) eq 'HASH') {
                   3321:                         $returnhash{$key}=$result;
                   3322:                     } else {
1.921     raeburn  3323:                         my @responses = split(/:/,$value);
                   3324:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3325:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3326:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3327:                         }
1.1008    raeburn  3328:                     }
1.353     www      3329:                 }
                   3330:             }
                   3331:         }
                   3332:     }
                   3333:     return %returnhash;
                   3334: }
                   3335: 
1.1055    raeburn  3336: sub courselastaccess {
                   3337:     my ($cdom,$cnum,$hostidref) = @_;
                   3338:     my %returnhash;
                   3339:     if ($cdom && $cnum) {
                   3340:         my $chome = &homeserver($cnum,$cdom);
                   3341:         if ($chome ne 'no_host') {
                   3342:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3343:             &extract_lastaccess(\%returnhash,$rep);
                   3344:         }
                   3345:     } else {
                   3346:         if (!$cdom) { $cdom=''; }
                   3347:         my %libserv = &all_library();
                   3348:         foreach my $tryserver (keys(%libserv)) {
                   3349:             if (ref($hostidref) eq 'ARRAY') {
                   3350:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3351:             } 
                   3352:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3353:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3354:                 &extract_lastaccess(\%returnhash,$rep);
                   3355:             }
                   3356:         }
                   3357:     }
                   3358:     return %returnhash;
                   3359: }
                   3360: 
                   3361: sub extract_lastaccess {
                   3362:     my ($returnhash,$rep) = @_;
                   3363:     if (ref($returnhash) eq 'HASH') {
                   3364:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3365:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3366:                  $rep eq '') {
                   3367:             my @pairs=split(/\&/,$rep);
                   3368:             foreach my $item (@pairs) {
                   3369:                 my ($key,$value)=split(/\=/,$item,2);
                   3370:                 $key = &unescape($key);
                   3371:                 next if ($key =~ /^error: 2 /);
                   3372:                 $returnhash->{$key} = &thaw_unescape($value);
                   3373:             }
                   3374:         }
                   3375:     }
                   3376:     return;
                   3377: }
                   3378: 
1.658     raeburn  3379: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3380: 
                   3381: sub dcmailput {
1.685     raeburn  3382:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3383:     my $status = &Apache::lonnet::critical(
1.740     www      3384:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3385:        &escape($message),$server);
1.662     raeburn  3386:     return $status;
                   3387: }
                   3388: 
1.658     raeburn  3389: sub dcmaildump {
                   3390:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3391:     my %returnhash=();
1.846     albertel 3392: 
                   3393:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3394:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3395:                                                          &escape($enddate).':';
                   3396: 	my @esc_senders=map { &escape($_)} @$senders;
                   3397: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3398: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3399:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3400:             if (($key) && ($value)) {
                   3401:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3402:             }
                   3403:         }
                   3404:     }
                   3405:     return %returnhash;
                   3406: }
1.662     raeburn  3407: # ---------------------------------------------------------- Domain roles
                   3408: 
                   3409: sub get_domain_roles {
                   3410:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3411:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3412:         $startdate = '.';
                   3413:     }
1.1018    raeburn  3414:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3415:         $enddate = '.';
                   3416:     }
1.922     raeburn  3417:     my $rolelist;
                   3418:     if (ref($roles) eq 'ARRAY') {
                   3419:         $rolelist = join(':',@{$roles});
                   3420:     }
1.662     raeburn  3421:     my %personnel = ();
1.841     albertel 3422: 
                   3423:     my %servers = &get_servers($dom,'library');
                   3424:     foreach my $tryserver (keys(%servers)) {
                   3425: 	%{$personnel{$tryserver}}=();
                   3426: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3427: 					    &escape($startdate).':'.
                   3428: 					    &escape($enddate).':'.
                   3429: 					    &escape($rolelist), $tryserver))) {
                   3430: 	    my ($key,$value) = split(/\=/,$line,2);
                   3431: 	    if (($key) && ($value)) {
                   3432: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3433: 	    }
                   3434: 	}
1.662     raeburn  3435:     }
                   3436:     return %personnel;
                   3437: }
1.658     raeburn  3438: 
1.149     www      3439: # ----------------------------------------------------------- Check out an item
                   3440: 
1.504     albertel 3441: sub get_first_access {
                   3442:     my ($type,$argsymb)=@_;
1.790     albertel 3443:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3444:     if ($argsymb) { $symb=$argsymb; }
                   3445:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3446:     if ($type eq 'course') {
                   3447: 	$res='course';
                   3448:     } elsif ($type eq 'map') {
1.588     albertel 3449: 	$res=&symbread($map);
                   3450:     } else {
                   3451: 	$res=$symb;
                   3452:     }
                   3453:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3454:     return $times{"$courseid\0$res"};
1.504     albertel 3455: }
                   3456: 
                   3457: sub set_first_access {
                   3458:     my ($type)=@_;
1.790     albertel 3459:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3460:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3461:     if ($type eq 'course') {
                   3462: 	$res='course';
                   3463:     } elsif ($type eq 'map') {
1.588     albertel 3464: 	$res=&symbread($map);
                   3465:     } else {
                   3466: 	$res=$symb;
                   3467:     }
                   3468:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3469:     if (!$firstaccess) {
1.588     albertel 3470: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3471:     }
                   3472:     return 'already_set';
1.504     albertel 3473: }
                   3474: 
1.149     www      3475: sub checkout {
                   3476:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3477:     my $now=time;
                   3478:     my $lonhost=$perlvar{'lonHostID'};
                   3479:     my $infostr=&escape(
1.234     www      3480:                  'CHECKOUTTOKEN&'.
1.149     www      3481:                  $tuname.'&'.
                   3482:                  $tudom.'&'.
                   3483:                  $tcrsid.'&'.
                   3484:                  $symb.'&'.
                   3485: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3486:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3487:     if ($token=~/^error\:/) { 
1.672     albertel 3488:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3489:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3490:                  "</font>");
                   3491:         return ''; 
                   3492:     }
                   3493: 
1.149     www      3494:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3495:     $token=~tr/a-z/A-Z/;
                   3496: 
1.153     www      3497:     my %infohash=('resource.0.outtoken' => $token,
                   3498:                   'resource.0.checkouttime' => $now,
                   3499:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3500: 
                   3501:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3502:        return '';
1.151     www      3503:     } else {
1.672     albertel 3504:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3505:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3506:                  "</font>");
1.149     www      3507:     }    
                   3508: 
                   3509:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3510:                          &escape('Checkout '.$infostr.' - '.
                   3511:                                                  $token)) ne 'ok') {
                   3512: 	return '';
1.151     www      3513:     } else {
1.672     albertel 3514:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3515:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3516:                  "</font>");
1.149     www      3517:     }
1.151     www      3518:     return $token;
1.149     www      3519: }
                   3520: 
                   3521: # ------------------------------------------------------------ Check in an item
                   3522: 
                   3523: sub checkin {
                   3524:     my $token=shift;
1.150     www      3525:     my $now=time;
                   3526:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3527:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3528:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3529:     $dtoken=~s/\W/\_/g;
1.234     www      3530:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3531:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3532: 
1.154     www      3533:     unless (($tuname) && ($tudom)) {
                   3534:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3535:         return '';
                   3536:     }
                   3537:     
                   3538:     unless (&allowed('mgr',$tcrsid)) {
                   3539:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3540:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3541:         return '';
                   3542:     }
                   3543: 
1.153     www      3544:     my %infohash=('resource.0.intoken' => $token,
                   3545:                   'resource.0.checkintime' => $now,
                   3546:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3547: 
                   3548:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3549:        return '';
                   3550:     }    
                   3551: 
                   3552:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3553:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3554: 	return '';
                   3555:     }
                   3556: 
                   3557:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3558: }
                   3559: 
                   3560: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3561: 
                   3562: sub expirespread {
                   3563:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3564:     my $cid=$env{'request.course.id'}; 
1.110     www      3565:     if ($cid) {
                   3566:        my $now=time;
                   3567:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3568:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3569:                             $env{'course.'.$cid.'.num'}.
1.110     www      3570: 	        	    ':nohist_expirationdates:'.
                   3571:                             &escape($key).'='.$now,
1.620     albertel 3572:                             $env{'course.'.$cid.'.home'})
1.110     www      3573:     }
                   3574:     return 'ok';
1.14      www      3575: }
                   3576: 
1.109     www      3577: # ----------------------------------------------------- Devalidate Spreadsheets
                   3578: 
                   3579: sub devalidate {
1.325     www      3580:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3581:     my $cid=$env{'request.course.id'}; 
1.109     www      3582:     if ($cid) {
1.391     matthew  3583:         # delete the stored spreadsheets for
                   3584:         # - the student level sheet of this user in course's homespace
                   3585:         # - the assessment level sheet for this resource 
                   3586:         #   for this user in user's homespace
1.553     albertel 3587: 	# - current conditional state info
1.325     www      3588: 	my $key=$uname.':'.$udom.':';
1.109     www      3589:         my $status=
1.299     matthew  3590: 	    &del('nohist_calculatedsheets',
1.391     matthew  3591: 		 [$key.'studentcalc:'],
1.620     albertel 3592: 		 $env{'course.'.$cid.'.domain'},
                   3593: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3594: 		.' '.
                   3595: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3596: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3597:         unless ($status eq 'ok ok') {
                   3598:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3599:                     $uname.' at '.$udom.' for '.
1.109     www      3600: 		    $symb.': '.$status);
1.133     albertel 3601:         }
1.553     albertel 3602: 	&delenv('user.state.'.$cid);
1.109     www      3603:     }
                   3604: }
                   3605: 
1.265     albertel 3606: sub get_scalar {
                   3607:     my ($string,$end) = @_;
                   3608:     my $value;
                   3609:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3610: 	$value = $1;
                   3611:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3612: 	$value = $1;
                   3613:     }
                   3614:     return &unescape($value);
                   3615: }
                   3616: 
                   3617: sub array2str {
                   3618:   my (@array) = @_;
                   3619:   my $result=&arrayref2str(\@array);
                   3620:   $result=~s/^__ARRAY_REF__//;
                   3621:   $result=~s/__END_ARRAY_REF__$//;
                   3622:   return $result;
                   3623: }
                   3624: 
1.204     albertel 3625: sub arrayref2str {
                   3626:   my ($arrayref) = @_;
1.265     albertel 3627:   my $result='__ARRAY_REF__';
1.204     albertel 3628:   foreach my $elem (@$arrayref) {
1.265     albertel 3629:     if(ref($elem) eq 'ARRAY') {
                   3630:       $result.=&arrayref2str($elem).'&';
                   3631:     } elsif(ref($elem) eq 'HASH') {
                   3632:       $result.=&hashref2str($elem).'&';
                   3633:     } elsif(ref($elem)) {
                   3634:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3635:     } else {
                   3636:       $result.=&escape($elem).'&';
                   3637:     }
                   3638:   }
                   3639:   $result=~s/\&$//;
1.265     albertel 3640:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3641:   return $result;
                   3642: }
                   3643: 
1.168     albertel 3644: sub hash2str {
1.204     albertel 3645:   my (%hash) = @_;
                   3646:   my $result=&hashref2str(\%hash);
1.265     albertel 3647:   $result=~s/^__HASH_REF__//;
                   3648:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3649:   return $result;
                   3650: }
                   3651: 
                   3652: sub hashref2str {
                   3653:   my ($hashref)=@_;
1.265     albertel 3654:   my $result='__HASH_REF__';
1.800     albertel 3655:   foreach my $key (sort(keys(%$hashref))) {
                   3656:     if (ref($key) eq 'ARRAY') {
                   3657:       $result.=&arrayref2str($key).'=';
                   3658:     } elsif (ref($key) eq 'HASH') {
                   3659:       $result.=&hashref2str($key).'=';
                   3660:     } elsif (ref($key)) {
1.265     albertel 3661:       $result.='=';
1.800     albertel 3662:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3663:     } else {
1.800     albertel 3664: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3665:     }
                   3666: 
1.800     albertel 3667:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3668:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3669:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3670:       $result.=&hashref2str($hashref->{$key}).'&';
                   3671:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3672:        $result.='&';
1.800     albertel 3673:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3674:     } else {
1.800     albertel 3675:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3676:     }
                   3677:   }
1.168     albertel 3678:   $result=~s/\&$//;
1.265     albertel 3679:   $result .= '__END_HASH_REF__';
1.168     albertel 3680:   return $result;
                   3681: }
                   3682: 
                   3683: sub str2hash {
1.265     albertel 3684:     my ($string)=@_;
                   3685:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3686:     return %$hash;
                   3687: }
                   3688: 
                   3689: sub str2hashref {
1.168     albertel 3690:   my ($string) = @_;
1.265     albertel 3691: 
                   3692:   my %hash;
                   3693: 
                   3694:   if($string !~ /^__HASH_REF__/) {
                   3695:       if (! ($string eq '' || !defined($string))) {
                   3696: 	  $hash{'error'}='Not hash reference';
                   3697:       }
                   3698:       return (\%hash, $string);
                   3699:   }
                   3700: 
                   3701:   $string =~ s/^__HASH_REF__//;
                   3702: 
                   3703:   while($string !~ /^__END_HASH_REF__/) {
                   3704:       #key
                   3705:       my $key='';
                   3706:       if($string =~ /^__HASH_REF__/) {
                   3707:           ($key, $string)=&str2hashref($string);
                   3708:           if(defined($key->{'error'})) {
                   3709:               $hash{'error'}='Bad data';
                   3710:               return (\%hash, $string);
                   3711:           }
                   3712:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3713:           ($key, $string)=&str2arrayref($string);
                   3714:           if($key->[0] eq 'Array reference error') {
                   3715:               $hash{'error'}='Bad data';
                   3716:               return (\%hash, $string);
                   3717:           }
                   3718:       } else {
                   3719:           $string =~ s/^(.*?)=//;
1.267     albertel 3720: 	  $key=&unescape($1);
1.265     albertel 3721:       }
                   3722:       $string =~ s/^=//;
                   3723: 
                   3724:       #value
                   3725:       my $value='';
                   3726:       if($string =~ /^__HASH_REF__/) {
                   3727:           ($value, $string)=&str2hashref($string);
                   3728:           if(defined($value->{'error'})) {
                   3729:               $hash{'error'}='Bad data';
                   3730:               return (\%hash, $string);
                   3731:           }
                   3732:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3733:           ($value, $string)=&str2arrayref($string);
                   3734:           if($value->[0] eq 'Array reference error') {
                   3735:               $hash{'error'}='Bad data';
                   3736:               return (\%hash, $string);
                   3737:           }
                   3738:       } else {
                   3739: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3740:       }
                   3741:       $string =~ s/^&//;
                   3742: 
                   3743:       $hash{$key}=$value;
1.204     albertel 3744:   }
1.265     albertel 3745: 
                   3746:   $string =~ s/^__END_HASH_REF__//;
                   3747: 
                   3748:   return (\%hash, $string);
1.204     albertel 3749: }
                   3750: 
                   3751: sub str2array {
1.265     albertel 3752:     my ($string)=@_;
                   3753:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3754:     return @$array;
                   3755: }
                   3756: 
                   3757: sub str2arrayref {
1.204     albertel 3758:   my ($string) = @_;
1.265     albertel 3759:   my @array;
                   3760: 
                   3761:   if($string !~ /^__ARRAY_REF__/) {
                   3762:       if (! ($string eq '' || !defined($string))) {
                   3763: 	  $array[0]='Array reference error';
                   3764:       }
                   3765:       return (\@array, $string);
                   3766:   }
                   3767: 
                   3768:   $string =~ s/^__ARRAY_REF__//;
                   3769: 
                   3770:   while($string !~ /^__END_ARRAY_REF__/) {
                   3771:       my $value='';
                   3772:       if($string =~ /^__HASH_REF__/) {
                   3773:           ($value, $string)=&str2hashref($string);
                   3774:           if(defined($value->{'error'})) {
                   3775:               $array[0] ='Array reference error';
                   3776:               return (\@array, $string);
                   3777:           }
                   3778:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3779:           ($value, $string)=&str2arrayref($string);
                   3780:           if($value->[0] eq 'Array reference error') {
                   3781:               $array[0] ='Array reference error';
                   3782:               return (\@array, $string);
                   3783:           }
                   3784:       } else {
                   3785: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3786:       }
                   3787:       $string =~ s/^&//;
                   3788: 
                   3789:       push(@array, $value);
1.191     harris41 3790:   }
1.265     albertel 3791: 
                   3792:   $string =~ s/^__END_ARRAY_REF__//;
                   3793: 
                   3794:   return (\@array, $string);
1.168     albertel 3795: }
                   3796: 
1.167     albertel 3797: # -------------------------------------------------------------------Temp Store
                   3798: 
1.168     albertel 3799: sub tmpreset {
                   3800:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3801:   if (!$symb) {
                   3802:     $symb=&symbread();
1.620     albertel 3803:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3804:   }
                   3805:   $symb=escape($symb);
                   3806: 
1.620     albertel 3807:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3808:   $namespace=~s/\//\_/g;
                   3809:   $namespace=~s/\W//g;
                   3810: 
1.620     albertel 3811:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3812:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3813:   if ($domain eq 'public' && $stuname eq 'public') {
                   3814:       $stuname=$ENV{'REMOTE_ADDR'};
                   3815:   }
1.168     albertel 3816:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3817:   my %hash;
                   3818:   if (tie(%hash,'GDBM_File',
                   3819: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3820: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3821:     foreach my $key (keys(%hash)) {
1.180     albertel 3822:       if ($key=~ /:$symb/) {
1.168     albertel 3823: 	delete($hash{$key});
                   3824:       }
                   3825:     }
                   3826:   }
                   3827: }
                   3828: 
1.167     albertel 3829: sub tmpstore {
1.168     albertel 3830:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3831: 
                   3832:   if (!$symb) {
                   3833:     $symb=&symbread();
1.620     albertel 3834:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3835:   }
                   3836:   $symb=escape($symb);
                   3837: 
                   3838:   if (!$namespace) {
                   3839:     # I don't think we would ever want to store this for a course.
                   3840:     # it seems this will only be used if we don't have a course.
1.620     albertel 3841:     #$namespace=$env{'request.course.id'};
1.168     albertel 3842:     #if (!$namespace) {
1.620     albertel 3843:       $namespace=$env{'request.state'};
1.168     albertel 3844:     #}
                   3845:   }
                   3846:   $namespace=~s/\//\_/g;
                   3847:   $namespace=~s/\W//g;
1.620     albertel 3848:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3849:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3850:   if ($domain eq 'public' && $stuname eq 'public') {
                   3851:       $stuname=$ENV{'REMOTE_ADDR'};
                   3852:   }
1.168     albertel 3853:   my $now=time;
                   3854:   my %hash;
                   3855:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3856:   if (tie(%hash,'GDBM_File',
                   3857: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3858: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3859:     $hash{"version:$symb"}++;
                   3860:     my $version=$hash{"version:$symb"};
                   3861:     my $allkeys=''; 
                   3862:     foreach my $key (keys(%$storehash)) {
                   3863:       $allkeys.=$key.':';
1.591     albertel 3864:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3865:     }
                   3866:     $hash{"$version:$symb:timestamp"}=$now;
                   3867:     $allkeys.='timestamp';
                   3868:     $hash{"$version:keys:$symb"}=$allkeys;
                   3869:     if (untie(%hash)) {
                   3870:       return 'ok';
                   3871:     } else {
                   3872:       return "error:$!";
                   3873:     }
                   3874:   } else {
                   3875:     return "error:$!";
                   3876:   }
                   3877: }
1.167     albertel 3878: 
1.168     albertel 3879: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3880: 
1.168     albertel 3881: sub tmprestore {
                   3882:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3883: 
1.168     albertel 3884:   if (!$symb) {
                   3885:     $symb=&symbread();
1.620     albertel 3886:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3887:   }
                   3888:   $symb=escape($symb);
                   3889: 
1.620     albertel 3890:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3891: 
1.620     albertel 3892:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3893:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3894:   if ($domain eq 'public' && $stuname eq 'public') {
                   3895:       $stuname=$ENV{'REMOTE_ADDR'};
                   3896:   }
1.168     albertel 3897:   my %returnhash;
                   3898:   $namespace=~s/\//\_/g;
                   3899:   $namespace=~s/\W//g;
                   3900:   my %hash;
                   3901:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3902:   if (tie(%hash,'GDBM_File',
                   3903: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3904: 	  &GDBM_READER(),0640)) {
1.168     albertel 3905:     my $version=$hash{"version:$symb"};
                   3906:     $returnhash{'version'}=$version;
                   3907:     my $scope;
                   3908:     for ($scope=1;$scope<=$version;$scope++) {
                   3909:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3910:       my @keys=split(/:/,$vkeys);
                   3911:       my $key;
                   3912:       $returnhash{"$scope:keys"}=$vkeys;
                   3913:       foreach $key (@keys) {
1.591     albertel 3914: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3915: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3916:       }
                   3917:     }
1.168     albertel 3918:     if (!(untie(%hash))) {
                   3919:       return "error:$!";
                   3920:     }
                   3921:   } else {
                   3922:     return "error:$!";
                   3923:   }
                   3924:   return %returnhash;
1.167     albertel 3925: }
                   3926: 
1.9       www      3927: # ----------------------------------------------------------------------- Store
                   3928: 
                   3929: sub store {
1.124     www      3930:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3931:     my $home='';
                   3932: 
1.168     albertel 3933:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3934: 
1.213     www      3935:     $symb=&symbclean($symb);
1.122     albertel 3936:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3937: 
1.620     albertel 3938:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3939:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3940: 
                   3941:     &devalidate($symb,$stuname,$domain);
1.109     www      3942: 
                   3943:     $symb=escape($symb);
1.187     www      3944:     if (!$namespace) { 
1.620     albertel 3945:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3946:           return ''; 
                   3947:        } 
                   3948:     }
1.620     albertel 3949:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3950: 
                   3951:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3952:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3953: 
1.12      www      3954:     my $namevalue='';
1.800     albertel 3955:     foreach my $key (keys(%$storehash)) {
                   3956:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3957:     }
1.12      www      3958:     $namevalue=~s/\&$//;
1.187     www      3959:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3960:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3961: }
                   3962: 
1.47      www      3963: # -------------------------------------------------------------- Critical Store
                   3964: 
                   3965: sub cstore {
1.124     www      3966:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3967:     my $home='';
                   3968: 
1.168     albertel 3969:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3970: 
1.213     www      3971:     $symb=&symbclean($symb);
1.122     albertel 3972:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3973: 
1.620     albertel 3974:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3975:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3976: 
                   3977:     &devalidate($symb,$stuname,$domain);
1.109     www      3978: 
                   3979:     $symb=escape($symb);
1.187     www      3980:     if (!$namespace) { 
1.620     albertel 3981:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3982:           return ''; 
                   3983:        } 
                   3984:     }
1.620     albertel 3985:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3986: 
                   3987:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3988:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3989: 
1.47      www      3990:     my $namevalue='';
1.800     albertel 3991:     foreach my $key (keys(%$storehash)) {
                   3992:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3993:     }
1.47      www      3994:     $namevalue=~s/\&$//;
1.187     www      3995:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3996:     return critical
                   3997:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3998: }
                   3999: 
1.9       www      4000: # --------------------------------------------------------------------- Restore
                   4001: 
                   4002: sub restore {
1.124     www      4003:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4004:     my $home='';
                   4005: 
1.168     albertel 4006:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4007: 
1.122     albertel 4008:     if (!$symb) {
                   4009:       unless ($symb=escape(&symbread())) { return ''; }
                   4010:     } else {
1.213     www      4011:       $symb=&escape(&symbclean($symb));
1.122     albertel 4012:     }
1.188     www      4013:     if (!$namespace) { 
1.620     albertel 4014:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4015:           return ''; 
                   4016:        } 
                   4017:     }
1.620     albertel 4018:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4019:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4020:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4021:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4022: 
1.12      www      4023:     my %returnhash=();
1.800     albertel 4024:     foreach my $line (split(/\&/,$answer)) {
                   4025: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4026:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4027:     }
1.75      www      4028:     my $version;
                   4029:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4030:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4031:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4032:        }
1.75      www      4033:     }
1.13      www      4034:     return %returnhash;
1.34      www      4035: }
                   4036: 
                   4037: # ---------------------------------------------------------- Course Description
                   4038: 
                   4039: sub coursedescription {
1.731     albertel 4040:     my ($courseid,$args)=@_;
1.34      www      4041:     $courseid=~s/^\///;
1.49      www      4042:     $courseid=~s/\_/\//g;
1.34      www      4043:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4044:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4045:     my $normalid=$cdomain.'_'.$cnum;
                   4046:     # need to always cache even if we get errors otherwise we keep 
                   4047:     # trying and trying and trying to get the course description.
                   4048:     my %envhash=();
                   4049:     my %returnhash=();
1.731     albertel 4050:     
                   4051:     my $expiretime=600;
                   4052:     if ($env{'request.course.id'} eq $normalid) {
                   4053: 	$expiretime=120;
                   4054:     }
                   4055: 
                   4056:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4057:     if (!$args->{'freshen_cache'}
                   4058: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4059: 	foreach my $key (keys(%env)) {
                   4060: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4061: 	    my ($setting) = $1;
                   4062: 	    $returnhash{$setting} = $env{$key};
                   4063: 	}
                   4064: 	return %returnhash;
                   4065:     }
                   4066: 
                   4067:     # get the data agin
                   4068:     if (!$args->{'one_time'}) {
                   4069: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4070:     }
1.811     albertel 4071: 
1.34      www      4072:     if ($chome ne 'no_host') {
1.302     albertel 4073:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4074:        if (!exists($returnhash{'con_lost'})) {
                   4075:            $returnhash{'home'}= $chome;
                   4076: 	   $returnhash{'domain'} = $cdomain;
                   4077: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4078:            if (!defined($returnhash{'type'})) {
                   4079:                $returnhash{'type'} = 'Course';
                   4080:            }
1.130     albertel 4081:            while (my ($name,$value) = each %returnhash) {
1.53      www      4082:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4083:            }
1.270     www      4084:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4085:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4086: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4087:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4088:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4089:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4090:        }
                   4091:     }
1.731     albertel 4092:     if (!$args->{'one_time'}) {
1.949     raeburn  4093: 	&appenv(\%envhash);
1.731     albertel 4094:     }
1.302     albertel 4095:     return %returnhash;
1.461     www      4096: }
                   4097: 
1.1056.4.5  raeburn  4098: sub update_released_required {
                   4099:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4100:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4101:         $cid = $env{'request.course.id'};
                   4102:         $cdom = $env{'course.'.$cid.'.domain'};
                   4103:         $cnum = $env{'course.'.$cid.'.num'};
                   4104:         $chome = $env{'course.'.$cid.'.home'};
                   4105:     }
                   4106:     if ($needsrelease) {
                   4107:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4108:         my $needsupdate;
                   4109:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4110:             $needsupdate = 1;
                   4111:         } else {
                   4112:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4113:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4114:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4115:                 $needsupdate = 1;
                   4116:             }
                   4117:         }
                   4118:         if ($needsupdate) {
                   4119:             my %needshash = (
                   4120:                              'internal.releaserequired' => $needsrelease,
                   4121:                             );
                   4122:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4123:             if ($putresult eq 'ok') {
                   4124:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4125:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4126:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4127:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4128:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4129:                 }
                   4130:             }
                   4131:         }
                   4132:     }
                   4133:     return;
                   4134: }
                   4135: 
1.461     www      4136: # -------------------------------------------------See if a user is privileged
                   4137: 
                   4138: sub privileged {
                   4139:     my ($username,$domain)=@_;
                   4140:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4141: 			&homeserver($username,$domain));
1.1033    raeburn  4142:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4143:         ($rolesdump =~ /^error:/)) {
                   4144:         return 0;
                   4145:     }
1.461     www      4146:     my $now=time;
                   4147:     if ($rolesdump ne '') {
1.800     albertel 4148:         foreach my $entry (split(/&/,$rolesdump)) {
                   4149: 	    if ($entry!~/^rolesdef_/) {
                   4150: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4151: 		$area=~s/\_\w\w$//;
                   4152: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4153: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4154: 		    my $active=1;
                   4155: 		    if ($tend) {
                   4156: 			if ($tend<$now) { $active=0; }
                   4157: 		    }
                   4158: 		    if ($tstart) {
                   4159: 			if ($tstart>$now) { $active=0; }
                   4160: 		    }
                   4161: 		    if ($active) { return 1; }
                   4162: 		}
                   4163: 	    }
                   4164: 	}
                   4165:     }
                   4166:     return 0;
1.9       www      4167: }
1.1       albertel 4168: 
1.103     harris41 4169: # -------------------------------------------------------- Get user privileges
1.11      www      4170: 
                   4171: sub rolesinit {
                   4172:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4173:     my $now=time;
                   4174:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4175:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4176:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4177:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4178:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4179:         return \%userroles;
                   4180:     }
1.11      www      4181:     my %allroles=();
1.678     raeburn  4182:     my %allgroups=();   
                   4183:     my $group_privs;
1.11      www      4184: 
                   4185:     if ($rolesdump ne '') {
1.800     albertel 4186:         foreach my $entry (split(/&/,$rolesdump)) {
                   4187: 	  if ($entry!~/^rolesdef_/) {
                   4188:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4189: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4190:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4191: 	    if ($role=~/^cr/) { 
1.807     albertel 4192: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4193: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4194: 		    ($tend,$tstart)=split('_',$trest);
                   4195: 		} else {
                   4196: 		    $trole=$role;
                   4197: 		}
1.678     raeburn  4198:             } elsif ($role =~ m|^gr/|) {
                   4199:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4200:                 ($trole,$group_privs) = split(/\//,$trole);
                   4201:                 $group_privs = &unescape($group_privs);
1.587     albertel 4202: 	    } else {
                   4203: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4204: 	    }
1.743     albertel 4205: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4206: 					 $username);
                   4207: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4208:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4209:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4210:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4211: 		my $spec=$trole.'.'.$area;
                   4212: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4213: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4214:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4215:                 } elsif ($trole eq 'gr') {
                   4216:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4217: 		} else {
1.567     raeburn  4218:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4219: 		}
1.12      www      4220:             }
1.662     raeburn  4221:           }
1.191     harris41 4222:         }
1.743     albertel 4223:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4224:         $userroles{'user.adv'}    = $adv;
                   4225: 	$userroles{'user.author'} = $author;
1.620     albertel 4226:         $env{'user.adv'}=$adv;
1.11      www      4227:     }
1.743     albertel 4228:     return \%userroles;  
1.11      www      4229: }
                   4230: 
1.567     raeburn  4231: sub set_arearole {
                   4232:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4233: # log the associated role with the area
                   4234:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4235:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4236: }
                   4237: 
                   4238: sub custom_roleprivs {
                   4239:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4240:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4241:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4242:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4243:         my ($rdummy,$roledef)=
                   4244:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4245:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4246:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4247:             if (defined($syspriv)) {
1.1043    raeburn  4248:                 if ($trest =~ /^$match_community$/) {
                   4249:                     $syspriv =~ s/bre\&S//; 
                   4250:                 }
1.567     raeburn  4251:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4252:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4253:             }
                   4254:             if ($tdomain ne '') {
                   4255:                 if (defined($dompriv)) {
                   4256:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4257:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4258:                 }
                   4259:                 if (($trest ne '') && (defined($coursepriv))) {
                   4260:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4261:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4262:                 }
                   4263:             }
                   4264:         }
                   4265:     }
                   4266: }
                   4267: 
1.678     raeburn  4268: sub group_roleprivs {
                   4269:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4270:     my $access = 1;
                   4271:     my $now = time;
                   4272:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4273:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4274:     if ($access) {
1.811     albertel 4275:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4276:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4277:     }
                   4278: }
1.567     raeburn  4279: 
                   4280: sub standard_roleprivs {
                   4281:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4282:     if (defined($pr{$trole.':s'})) {
                   4283:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4284:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4285:     }
                   4286:     if ($tdomain ne '') {
                   4287:         if (defined($pr{$trole.':d'})) {
                   4288:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4289:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4290:         }
                   4291:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4292:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4293:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4294:         }
                   4295:     }
                   4296: }
                   4297: 
                   4298: sub set_userprivs {
1.1056.4.2  raeburn  4299:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4300:     my $author=0;
                   4301:     my $adv=0;
1.678     raeburn  4302:     my %grouproles = ();
                   4303:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4304:         my @groupkeys;
1.1000    raeburn  4305:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4306:             push(@groupkeys,$role);
                   4307:         }
                   4308:         if (ref($groups_roles) eq 'HASH') {
                   4309:             foreach my $key (keys(%{$groups_roles})) {
                   4310:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4311:                     push(@groupkeys,$key);
                   4312:                 }
                   4313:             }
                   4314:         }
                   4315:         if (@groupkeys > 0) {
                   4316:             foreach my $role (@groupkeys) {
                   4317:                 my ($trole,$area,$sec,$extendedarea);
                   4318:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4319:                     $trole = $1;
                   4320:                     $area = $2;
                   4321:                     $sec = $3;
                   4322:                     $extendedarea = $area.$sec;
                   4323:                     if (exists($$allgroups{$area})) {
                   4324:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4325:                             my $spec = $trole.'.'.$extendedarea;
                   4326:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4327:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4328:                         }
1.678     raeburn  4329:                     }
                   4330:                 }
                   4331:             }
                   4332:         }
                   4333:     }
1.800     albertel 4334:     foreach my $group (keys(%grouproles)) {
                   4335:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4336:     }
1.800     albertel 4337:     foreach my $role (keys(%{$allroles})) {
                   4338:         my %thesepriv;
1.941     raeburn  4339:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4340:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4341:             if ($item ne '') {
                   4342:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4343:                 if ($restrictions eq '') {
                   4344:                     $thesepriv{$privilege}='F';
                   4345:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4346:                     $thesepriv{$privilege}.=$restrictions;
                   4347:                 }
                   4348:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4349:             }
                   4350:         }
                   4351:         my $thesestr='';
1.800     albertel 4352:         foreach my $priv (keys(%thesepriv)) {
                   4353: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4354: 	}
                   4355:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4356:     }
                   4357:     return ($author,$adv);
                   4358: }
                   4359: 
1.994     raeburn  4360: sub role_status {
1.1002    raeburn  4361:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4362:     my @pwhere = ();
                   4363:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4364:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4365:         unless (!defined($$role) || $$role eq '') {
                   4366:             $$where=join('.',@pwhere);
                   4367:             $$trolecode=$$role.'.'.$$where;
                   4368:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4369:             $$tstatus='is';
                   4370:             if ($$tstart && $$tstart>$then) {
                   4371:                 $$tstatus='future';
1.1034    raeburn  4372:                 if ($$tstart<$now) {
                   4373:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4374:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4375:                             my (%allroles,%allgroups,$group_privs,
                   4376:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4377:                             my %userroles = (
                   4378:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4379:                             );
1.1056.4.2  raeburn  4380:                             @rolecodes = ('cm');
1.1002    raeburn  4381:                             my $spec=$$role.'.'.$$where;
                   4382:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4383:                             if ($$role =~ /^cr\//) {
                   4384:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4385:                                 push(@rolecodes,'cr');
1.1002    raeburn  4386:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4387:                                 push(@rolecodes,$$role);
1.1002    raeburn  4388:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4389:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4390:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4391:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4392:                                 $group_privs = &unescape($group_privs);
                   4393:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4394:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4395:                                 if (keys(%course_roles) > 0) {
                   4396:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4397:                                     if ($tdomain ne '' && $tnum ne '') {
                   4398:                                         foreach my $key (keys(%course_roles)) {
                   4399:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4400:                                                 my $crsrole = $1;
                   4401:                                                 my $crssec = $2;
                   4402:                                                 if ($crsrole =~ /^cr/) {
                   4403:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4404:                                                         push(@rolecodes,'cr');
                   4405:                                                     }
                   4406:                                                 } else {
                   4407:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4408:                                                         push(@rolecodes,$crsrole);
                   4409:                                                     }
                   4410:                                                 }
                   4411:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4412:                                                 if ($crssec ne '') {
                   4413:                                                     $rolekey .= '/'.$crssec;
                   4414:                                                 }
                   4415:                                                 $rolekey .= './';
                   4416:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4417:                                             }
                   4418:                                         }
                   4419:                                     }
                   4420:                                 }
1.1002    raeburn  4421:                             } else {
1.1056.4.2  raeburn  4422:                                 push(@rolecodes,$$role);
1.1002    raeburn  4423:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4424:                             }
1.1056.4.2  raeburn  4425:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4426:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4427:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4428:                         }
                   4429:                     }
1.1034    raeburn  4430:                     $$tstatus = 'is';
1.1002    raeburn  4431:                 }
1.994     raeburn  4432:             }
                   4433:             if ($$tend) {
                   4434:                 if ($$tend<$then) {
                   4435:                     $$tstatus='expired';
                   4436:                 } elsif ($$tend<$now) {
                   4437:                     $$tstatus='will_not';
                   4438:                 }
                   4439:             }
                   4440:         }
                   4441:     }
                   4442: }
                   4443: 
                   4444: sub check_adhoc_privs {
1.1056.4.12  raeburn  4445:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4446:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4447:     if ($env{$cckey}) {
                   4448:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4449:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4450:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4451:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4452:         }
                   4453:     } else {
1.1056.4.12  raeburn  4454:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4455:     }
                   4456: }
                   4457: 
                   4458: sub set_adhoc_privileges {
                   4459: # role can be cc or ca
1.1056.4.12  raeburn  4460:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4461:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4462:     my $spec = $role.'.'.$area;
                   4463:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4464:                                   $env{'user.name'});
                   4465:     my %ccrole = ();
                   4466:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4467:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4468:     &appenv(\%userroles,[$role,'cm']);
                   4469:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4470:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4471:         &appenv( {'request.role'        => $spec,
                   4472:                   'request.role.domain' => $dcdom,
                   4473:                   'request.course.sec'  => ''
                   4474:                  }
                   4475:                );
                   4476:         my $tadv=0;
                   4477:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4478:         &appenv({'request.role.adv'    => $tadv});
                   4479:     }
1.994     raeburn  4480: }
                   4481: 
1.12      www      4482: # --------------------------------------------------------------- get interface
                   4483: 
                   4484: sub get {
1.131     albertel 4485:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4486:    my $items='';
1.800     albertel 4487:    foreach my $item (@$storearr) {
                   4488:        $items.=&escape($item).'&';
1.191     harris41 4489:    }
1.12      www      4490:    $items=~s/\&$//;
1.620     albertel 4491:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4492:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4493:    my $uhome=&homeserver($uname,$udomain);
                   4494: 
1.133     albertel 4495:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4496:    my @pairs=split(/\&/,$rep);
1.273     albertel 4497:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4498:      return @pairs;
                   4499:    }
1.15      www      4500:    my %returnhash=();
1.42      www      4501:    my $i=0;
1.800     albertel 4502:    foreach my $item (@$storearr) {
                   4503:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4504:       $i++;
1.191     harris41 4505:    }
1.15      www      4506:    return %returnhash;
1.27      www      4507: }
                   4508: 
                   4509: # --------------------------------------------------------------- del interface
                   4510: 
                   4511: sub del {
1.133     albertel 4512:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4513:    my $items='';
1.800     albertel 4514:    foreach my $item (@$storearr) {
                   4515:        $items.=&escape($item).'&';
1.191     harris41 4516:    }
1.984     neumanie 4517: 
1.27      www      4518:    $items=~s/\&$//;
1.620     albertel 4519:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4520:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4521:    my $uhome=&homeserver($uname,$udomain);
                   4522:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4523: }
                   4524: 
                   4525: # -------------------------------------------------------------- dump interface
                   4526: 
                   4527: sub dump {
1.1056.4.10  raeburn  4528:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4529:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4530:     if (!$uname) { $uname=$env{'user.name'}; }
                   4531:     my $uhome=&homeserver($uname,$udomain);
                   4532:     if ($regexp) {
                   4533: 	$regexp=&escape($regexp);
                   4534:     } else {
                   4535: 	$regexp='.';
                   4536:     }
1.1056.4.10  raeburn  4537:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4538:     my @pairs=split(/\&/,$rep);
                   4539:     my %returnhash=();
                   4540:     foreach my $item (@pairs) {
                   4541: 	my ($key,$value)=split(/=/,$item,2);
                   4542: 	$key = &unescape($key);
                   4543: 	next if ($key =~ /^error: 2 /);
                   4544: 	$returnhash{$key}=&thaw_unescape($value);
                   4545:     }
                   4546:     return %returnhash;
1.407     www      4547: }
                   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.688     albertel 4831: # ------------------------------------------------------------ tmpget interface
                   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.1056.4.1  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.1056.4.9  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.1056.4.9  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.1056.4.9  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.1056.4.10  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.689     albertel 5747: 	   if ($priv ne 'pch') { 
                   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.689     albertel 5757: 	   if ($priv ne 'pch') { 
                   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.689     albertel 5771: 	   if ($priv ne 'pch') { 
                   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.1056.4.4  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.508     raeburn  6124:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   6125:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  6126:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$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.1056.4.2  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.1056.4.10  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.1056.4.1  raeburn  6861:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6862:     $udom= &LONCAPA::clean_domain($udom);
                   6863:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  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.1056.4.1  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.1056.4.4  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.1056.4.4  raeburn  6934:     my (%names,%oldnames);
1.313     matthew  6935:     if ($tmp[0] =~ m/^error:.*/) { 
                   6936:         %names=(); 
                   6937:     } else {
                   6938:         %names = @tmp;
1.1056.4.4  raeburn  6939:         %oldnames = %names;
1.313     matthew  6940:     }
1.1056.4.6  raeburn  6941: #
1.1056.4.1  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.1056.4.4  raeburn  6993:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  6994:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  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.1056.4.4  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.1056.4.11  raeburn  7021:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7022:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7023:     }
1.1056.4.4  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/\&$//;
                   7343:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7344:                                   "$namespace:$datakey:$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 {
                   7397:     my ($file_name, $domain, $user) = @_;
                   7398:     my @check;
                   7399:     my $is_locked;
1.1056.4.14! 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}}) {
                   7409:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  7410:                $is_locked = 'true';
                   7411:                last;
1.745     raeburn  7412:            }
                   7413:        }
1.566     banghart 7414:     } else {
                   7415:         $is_locked = 'false';
                   7416:     }
1.1056.4.14! raeburn  7417:     return $is_locked;
1.566     banghart 7418: }
                   7419: 
1.759     albertel 7420: sub declutter_portfile {
                   7421:     my ($file) = @_;
1.833     albertel 7422:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7423:     return $file;
                   7424: }
                   7425: 
1.559     banghart 7426: # ------------------------------------------------------------- Mark as Read Only
                   7427: 
                   7428: sub mark_as_readonly {
                   7429:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7430:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7431:     my ($tmp)=keys(%current_permissions);
                   7432:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7433:     foreach my $file (@{$files}) {
1.759     albertel 7434: 	$file = &declutter_portfile($file);
1.561     banghart 7435:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7436:     }
1.613     albertel 7437:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7438:     return;
                   7439: }
                   7440: 
1.572     banghart 7441: # ------------------------------------------------------------Save Selected Files
                   7442: 
                   7443: sub save_selected_files {
                   7444:     my ($user, $path, @files) = @_;
                   7445:     my $filename = $user."savedfiles";
1.573     banghart 7446:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7447:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7448:     foreach my $file (@files) {
1.620     albertel 7449:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7450:     }
                   7451:     foreach my $file (@other_files) {
1.574     banghart 7452:         print (OUT $file."\n");
1.572     banghart 7453:     }
1.574     banghart 7454:     close (OUT);
1.572     banghart 7455:     return 'ok';
                   7456: }
                   7457: 
1.574     banghart 7458: sub clear_selected_files {
                   7459:     my ($user) = @_;
                   7460:     my $filename = $user."savedfiles";
                   7461:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7462:     print (OUT undef);
                   7463:     close (OUT);
                   7464:     return ("ok");    
                   7465: }
                   7466: 
1.572     banghart 7467: sub files_in_path {
                   7468:     my ($user, $path) = @_;
                   7469:     my $filename = $user."savedfiles";
                   7470:     my %return_files;
1.574     banghart 7471:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7472:     while (my $line_in = <IN>) {
1.574     banghart 7473:         chomp ($line_in);
                   7474:         my @paths_and_file = split (m!/!, $line_in);
                   7475:         my $file_part = pop (@paths_and_file);
                   7476:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7477:         $path_part.='/';
                   7478:         my $path_and_file = $path_part.$file_part;
                   7479:         if ($path_part eq $path) {
                   7480:             $return_files{$file_part}= 'selected';
                   7481:         }
                   7482:     }
1.574     banghart 7483:     close (IN);
                   7484:     return (\%return_files);
1.572     banghart 7485: }
                   7486: 
                   7487: # called in portfolio select mode, to show files selected NOT in current directory
                   7488: sub files_not_in_path {
                   7489:     my ($user, $path) = @_;
                   7490:     my $filename = $user."savedfiles";
                   7491:     my @return_files;
                   7492:     my $path_part;
1.800     albertel 7493:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7494:     while (my $line = <IN>) {
1.572     banghart 7495:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7496:         my @paths_and_file = split(m|/|, $line);
                   7497:         my $file_part = pop(@paths_and_file);
                   7498:         chomp($file_part);
                   7499:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7500:         $path_part .= '/';
                   7501:         my $path_and_file = $path_part.$file_part;
                   7502:         if ($path_part ne $path) {
1.800     albertel 7503:             push(@return_files, ($path_and_file));
1.572     banghart 7504:         }
                   7505:     }
1.800     albertel 7506:     close(OUT);
1.574     banghart 7507:     return (@return_files);
1.572     banghart 7508: }
                   7509: 
1.745     raeburn  7510: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7511: 
1.745     raeburn  7512: sub get_portfile_permissions {
                   7513:     my ($domain,$user) = @_;
1.613     albertel 7514:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7515:     my ($tmp)=keys(%current_permissions);
                   7516:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7517:     return \%current_permissions;
                   7518: }
                   7519: 
                   7520: #---------------------------------------------Get portfolio file access controls
                   7521: 
1.749     raeburn  7522: sub get_access_controls {
1.745     raeburn  7523:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7524:     my %access;
                   7525:     my $real_file = $file;
                   7526:     $file =~ s/\.meta$//;
1.745     raeburn  7527:     if (defined($file)) {
1.749     raeburn  7528:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7529:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7530:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7531:             }
                   7532:         }
1.745     raeburn  7533:     } else {
1.749     raeburn  7534:         foreach my $key (keys(%{$current_permissions})) {
                   7535:             if ($key =~ /\0accesscontrol$/) {
                   7536:                 if (defined($group)) {
                   7537:                     if ($key !~ m-^\Q$group\E/-) {
                   7538:                         next;
                   7539:                     }
                   7540:                 }
                   7541:                 my ($fullpath) = split(/\0/,$key);
                   7542:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7543:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7544:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7545:                     }
                   7546:                 }
                   7547:             }
                   7548:         }
                   7549:     }
                   7550:     return %access;
                   7551: }
                   7552: 
                   7553: sub modify_access_controls {
                   7554:     my ($file_name,$changes,$domain,$user)=@_;
                   7555:     my ($outcome,$deloutcome);
                   7556:     my %store_permissions;
                   7557:     my %new_values;
                   7558:     my %new_control;
                   7559:     my %translation;
                   7560:     my @deletions = ();
                   7561:     my $now = time;
                   7562:     if (exists($$changes{'activate'})) {
                   7563:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7564:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7565:             my $numnew = scalar(@newitems);
                   7566:             for (my $i=0; $i<$numnew; $i++) {
                   7567:                 my $newkey = $newitems[$i];
                   7568:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7569:                 if ($newkey =~ /^\d+:/) { 
                   7570:                     $newkey =~ s/^(\d+)/$newid/;
                   7571:                     $translation{$1} = $newid;
                   7572:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7573:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7574:                     $translation{$1} = $newid;
                   7575:                 }
1.749     raeburn  7576:                 $new_values{$file_name."\0".$newkey} = 
                   7577:                                           $$changes{'activate'}{$newitems[$i]};
                   7578:                 $new_control{$newkey} = $now;
                   7579:             }
                   7580:         }
                   7581:     }
                   7582:     my %todelete;
                   7583:     my %changed_items;
                   7584:     foreach my $action ('delete','update') {
                   7585:         if (exists($$changes{$action})) {
                   7586:             if (ref($$changes{$action}) eq 'HASH') {
                   7587:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7588:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7589:                     if ($action eq 'delete') { 
                   7590:                         $todelete{$itemnum} = 1;
                   7591:                     } else {
                   7592:                         $changed_items{$itemnum} = $key;
                   7593:                     }
                   7594:                 }
1.745     raeburn  7595:             }
                   7596:         }
1.749     raeburn  7597:     }
                   7598:     # get lock on access controls for file.
                   7599:     my $lockhash = {
                   7600:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7601:                                                        ':'.$env{'user.domain'},
                   7602:                    }; 
                   7603:     my $tries = 0;
                   7604:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7605:    
                   7606:     while (($gotlock ne 'ok') && $tries <3) {
                   7607:         $tries ++;
                   7608:         sleep 1;
                   7609:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7610:     }
                   7611:     if ($gotlock eq 'ok') {
                   7612:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7613:         my ($tmp)=keys(%curr_permissions);
                   7614:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7615:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7616:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7617:             if (ref($curr_controls) eq 'HASH') {
                   7618:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7619:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7620:                     if (defined($todelete{$itemnum})) {
                   7621:                         push(@deletions,$file_name."\0".$control_item);
                   7622:                     } else {
                   7623:                         if (defined($changed_items{$itemnum})) {
                   7624:                             $new_control{$changed_items{$itemnum}} = $now;
                   7625:                             push(@deletions,$file_name."\0".$control_item);
                   7626:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7627:                         } else {
                   7628:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7629:                         }
                   7630:                     }
1.745     raeburn  7631:                 }
                   7632:             }
                   7633:         }
1.970     raeburn  7634:         my ($group);
                   7635:         if (&is_course($domain,$user)) {
                   7636:             ($group,my $file) = split(/\//,$file_name,2);
                   7637:         }
1.749     raeburn  7638:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7639:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7640:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7641:         #  remove lock
                   7642:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7643:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7644:         my $sqlresult =
1.970     raeburn  7645:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7646:                                     $group);
1.749     raeburn  7647:     } else {
                   7648:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7649:     }
1.749     raeburn  7650:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7651: }
                   7652: 
1.827     raeburn  7653: sub make_public_indefinitely {
                   7654:     my ($requrl) = @_;
                   7655:     my $now = time;
                   7656:     my $action = 'activate';
                   7657:     my $aclnum = 0;
                   7658:     if (&is_portfolio_url($requrl)) {
                   7659:         my (undef,$udom,$unum,$file_name,$group) =
                   7660:             &parse_portfolio_url($requrl);
                   7661:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7662:         my %access_controls = &get_access_controls($current_perms,
                   7663:                                                    $group,$file_name);
                   7664:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7665:             my ($num,$scope,$end,$start) = 
                   7666:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7667:             if ($scope eq 'public') {
                   7668:                 if ($start <= $now && $end == 0) {
                   7669:                     $action = 'none';
                   7670:                 } else {
                   7671:                     $action = 'update';
                   7672:                     $aclnum = $num;
                   7673:                 }
                   7674:                 last;
                   7675:             }
                   7676:         }
                   7677:         if ($action eq 'none') {
                   7678:              return 'ok';
                   7679:         } else {
                   7680:             my %changes;
                   7681:             my $newend = 0;
                   7682:             my $newstart = $now;
                   7683:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7684:             $changes{$action}{$newkey} = {
                   7685:                 type => 'public',
                   7686:                 time => {
                   7687:                     start => $newstart,
                   7688:                     end   => $newend,
                   7689:                 },
                   7690:             };
                   7691:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7692:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7693:             return $outcome;
                   7694:         }
                   7695:     } else {
                   7696:         return 'invalid';
                   7697:     }
                   7698: }
                   7699: 
1.745     raeburn  7700: #------------------------------------------------------Get Marked as Read Only
                   7701: 
                   7702: sub get_marked_as_readonly {
                   7703:     my ($domain,$user,$what,$group) = @_;
                   7704:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7705:     my @readonly_files;
1.629     banghart 7706:     my $cmp1=$what;
                   7707:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7708:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7709:         if (defined($group)) {
                   7710:             if ($file_name !~ m-^\Q$group\E/-) {
                   7711:                 next;
                   7712:             }
                   7713:         }
1.561     banghart 7714:         if (ref($value) eq "ARRAY"){
                   7715:             foreach my $stored_what (@{$value}) {
1.629     banghart 7716:                 my $cmp2=$stored_what;
1.759     albertel 7717:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7718:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7719:                 }
1.629     banghart 7720:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7721:                     push(@readonly_files, $file_name);
1.745     raeburn  7722:                     last;
1.563     banghart 7723:                 } elsif (!defined($what)) {
                   7724:                     push(@readonly_files, $file_name);
1.745     raeburn  7725:                     last;
1.561     banghart 7726:                 }
                   7727:             }
1.745     raeburn  7728:         }
1.561     banghart 7729:     }
                   7730:     return @readonly_files;
                   7731: }
1.577     banghart 7732: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7733: 
1.577     banghart 7734: sub get_marked_as_readonly_hash {
1.745     raeburn  7735:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7736:     my %readonly_files;
1.745     raeburn  7737:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7738:         if (defined($group)) {
                   7739:             if ($file_name !~ m-^\Q$group\E/-) {
                   7740:                 next;
                   7741:             }
                   7742:         }
1.577     banghart 7743:         if (ref($value) eq "ARRAY"){
                   7744:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7745:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7746:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7747:                         if ($lock_descriptor eq 'graded') {
                   7748:                             $readonly_files{$file_name} = 'graded';
                   7749:                         } elsif ($lock_descriptor eq 'handback') {
                   7750:                             $readonly_files{$file_name} = 'handback';
                   7751:                         } else {
                   7752:                             if (!exists($readonly_files{$file_name})) {
                   7753:                                 $readonly_files{$file_name} = 'locked';
                   7754:                             }
                   7755:                         }
1.745     raeburn  7756:                     }
1.750     banghart 7757:                 } 
1.577     banghart 7758:             }
                   7759:         } 
                   7760:     }
                   7761:     return %readonly_files;
                   7762: }
1.559     banghart 7763: # ------------------------------------------------------------ Unmark as Read Only
                   7764: 
                   7765: sub unmark_as_readonly {
1.629     banghart 7766:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7767:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7768:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7769:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7770:     my $symb_crs = $what;
                   7771:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7772:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7773:     my ($tmp)=keys(%current_permissions);
                   7774:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7775:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7776:     foreach my $file (@readonly_files) {
1.759     albertel 7777: 	my $clean_file = &declutter_portfile($file);
                   7778: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7779: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7780:         my @new_locks;
                   7781:         my @del_keys;
                   7782:         if (ref($current_locks) eq "ARRAY"){
                   7783:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7784:                 my $compare=$locker;
1.749     raeburn  7785:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7786:                     $compare=join('',@{$locker});
1.746     raeburn  7787:                     if ($compare ne $symb_crs) {
                   7788:                         push(@new_locks, $locker);
                   7789:                     }
1.563     banghart 7790:                 }
                   7791:             }
1.650     albertel 7792:             if (scalar(@new_locks) > 0) {
1.563     banghart 7793:                 $current_permissions{$file} = \@new_locks;
                   7794:             } else {
                   7795:                 push(@del_keys, $file);
1.613     albertel 7796:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7797:                 delete($current_permissions{$file});
1.563     banghart 7798:             }
                   7799:         }
1.561     banghart 7800:     }
1.613     albertel 7801:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7802:     return;
                   7803: }
1.512     banghart 7804: 
1.17      www      7805: # ------------------------------------------------------------ Directory lister
                   7806: 
                   7807: sub dirlist {
1.955     raeburn  7808:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7809:     $uri=~s/^\///;
                   7810:     $uri=~s/\/$//;
1.253     stredwic 7811:     my ($udom, $uname);
1.955     raeburn  7812:     if ($getuserdir) {
1.253     stredwic 7813:         $udom = $userdomain;
                   7814:         $uname = $username;
1.955     raeburn  7815:     } else {
                   7816:         (undef,$udom,$uname)=split(/\//,$uri);
                   7817:         if(defined($userdomain)) {
                   7818:             $udom = $userdomain;
                   7819:         }
                   7820:         if(defined($username)) {
                   7821:             $uname = $username;
                   7822:         }
1.253     stredwic 7823:     }
1.955     raeburn  7824:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7825: 
1.955     raeburn  7826:     $dirRoot = $perlvar{'lonDocRoot'};
                   7827:     if (defined($getpropath)) {
                   7828:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7829:         $dirRoot =~ s/\/$//;
1.955     raeburn  7830:     } elsif (defined($getuserdir)) {
                   7831:         my $subdir=$uname.'__';
                   7832:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7833:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7834:                    ."/$udom/$subdir/$uname";
                   7835:     } elsif (defined($alternateRoot)) {
                   7836:         $dirRoot = $alternateRoot;
1.751     banghart 7837:     }
1.253     stredwic 7838: 
                   7839:     if($udom) {
                   7840:         if($uname) {
1.955     raeburn  7841:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7842:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7843:                               .':'.&escape($uname).':'.&escape($udom),
                   7844:                               &homeserver($uname,$udom));
                   7845:             if ($listing eq 'unknown_cmd') {
                   7846:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7847:                                   &homeserver($uname,$udom));
                   7848:             } else {
                   7849:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7850:             }
1.605     matthew  7851:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7852:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7853: 				  &homeserver($uname,$udom));
1.605     matthew  7854:                 @listing_results = split(/:/,$listing);
                   7855:             } else {
                   7856:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7857:             }
                   7858:             return @listing_results;
1.955     raeburn  7859:         } elsif(!$alternateRoot) {
1.800     albertel 7860:             my %allusers;
1.841     albertel 7861: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7862:  	    foreach my $tryserver (keys(%servers)) {
                   7863:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7864:                                   &escape($udom),$tryserver);
                   7865:                 if ($listing eq 'unknown_cmd') {
                   7866: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7867: 				      $udom, $tryserver);
                   7868:                 } else {
                   7869:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7870:                 }
1.841     albertel 7871: 		if ($listing eq 'unknown_cmd') {
                   7872: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7873: 				      $udom, $tryserver);
                   7874: 		    @listing_results = split(/:/,$listing);
                   7875: 		} else {
                   7876: 		    @listing_results =
                   7877: 			map { &unescape($_); } split(/:/,$listing);
                   7878: 		}
                   7879: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7880: 		    $listing_results[0] ne 'empty'       &&
                   7881: 		    $listing_results[0] ne 'con_lost') {
                   7882: 		    foreach my $line (@listing_results) {
                   7883: 			my ($entry) = split(/&/,$line,2);
                   7884: 			$allusers{$entry} = 1;
                   7885: 		    }
                   7886: 		}
1.253     stredwic 7887:             }
                   7888:             my $alluserstr='';
1.800     albertel 7889:             foreach my $user (sort(keys(%allusers))) {
                   7890:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7891:             }
                   7892:             $alluserstr=~s/:$//;
                   7893:             return split(/:/,$alluserstr);
                   7894:         } else {
1.800     albertel 7895:             return ('missing user name');
1.253     stredwic 7896:         }
1.955     raeburn  7897:     } elsif(!defined($getpropath)) {
1.841     albertel 7898:         my @all_domains = sort(&all_domains());
1.955     raeburn  7899:         foreach my $domain (@all_domains) {
                   7900:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7901:         }
                   7902:         return @all_domains;
                   7903:     } else {
1.800     albertel 7904:         return ('missing domain');
1.275     stredwic 7905:     }
                   7906: }
                   7907: 
                   7908: # --------------------------------------------- GetFileTimestamp
                   7909: # This function utilizes dirlist and returns the date stamp for
                   7910: # when it was last modified.  It will also return an error of -1
                   7911: # if an error occurs
                   7912: 
                   7913: sub GetFileTimestamp {
1.955     raeburn  7914:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7915:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7916:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7917:     my ($fileStat) = 
                   7918:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7919:                                  undef,$getuserdir);
1.275     stredwic 7920:     my @stats = split('&', $fileStat);
                   7921:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7922:         # @stats contains first the filename, then the stat output
                   7923:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7924:     } else {
                   7925:         return -1;
1.253     stredwic 7926:     }
1.26      www      7927: }
                   7928: 
1.712     albertel 7929: sub stat_file {
                   7930:     my ($uri) = @_;
1.787     albertel 7931:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7932: 
1.955     raeburn  7933:     my ($udom,$uname,$file);
1.712     albertel 7934:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7935: 	($udom,$uname,$file) =
1.811     albertel 7936: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7937: 	$file = 'userfiles/'.$file;
                   7938:     }
                   7939:     if ($uri =~ m-^/res/-) {
                   7940: 	($udom,$uname) = 
1.807     albertel 7941: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7942: 	$file = $uri;
                   7943:     }
                   7944: 
                   7945:     if (!$udom || !$uname || !$file) {
                   7946: 	# unable to handle the uri
                   7947: 	return ();
                   7948:     }
1.956     raeburn  7949:     my $getpropath;
                   7950:     if ($file =~ /^userfiles\//) {
                   7951:         $getpropath = 1;
                   7952:     }
1.955     raeburn  7953:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7954:     my @stats = split('&', $result);
1.721     banghart 7955:     
1.712     albertel 7956:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7957: 	shift(@stats); #filename is first
                   7958: 	return @stats;
                   7959:     }
                   7960:     return ();
                   7961: }
                   7962: 
1.26      www      7963: # -------------------------------------------------------- Value of a Condition
                   7964: 
1.713     albertel 7965: # gets the value of a specific preevaluated condition
                   7966: #    stored in the string  $env{user.state.<cid>}
                   7967: # or looks up a condition reference in the bighash and if if hasn't
                   7968: # already been evaluated recurses into docondval to get the value of
                   7969: # the condition, then memoizing it to 
                   7970: #   $env{user.state.<cid>.<condition>}
1.40      www      7971: sub directcondval {
                   7972:     my $number=shift;
1.620     albertel 7973:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7974: 	&Apache::lonuserstate::evalstate();
                   7975:     }
1.713     albertel 7976:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7977: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7978:     } elsif ($number =~ /^_/) {
                   7979: 	my $sub_condition;
                   7980: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7981: 		&GDBM_READER(),0640)) {
                   7982: 	    $sub_condition=$bighash{'conditions'.$number};
                   7983: 	    untie(%bighash);
                   7984: 	}
                   7985: 	my $value = &docondval($sub_condition);
1.949     raeburn  7986: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7987: 	return $value;
                   7988:     }
1.620     albertel 7989:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7990:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7991:     } else {
                   7992:        return 2;
                   7993:     }
                   7994: }
                   7995: 
1.713     albertel 7996: # get the collection of conditions for this resource
1.26      www      7997: sub condval {
                   7998:     my $condidx=shift;
1.54      www      7999:     my $allpathcond='';
1.713     albertel 8000:     foreach my $cond (split(/\|/,$condidx)) {
                   8001: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8002: 	    $allpathcond.=
                   8003: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8004: 	}
1.191     harris41 8005:     }
1.54      www      8006:     $allpathcond=~s/\|$//;
1.713     albertel 8007:     return &docondval($allpathcond);
                   8008: }
                   8009: 
                   8010: #evaluates an expression of conditions
                   8011: sub docondval {
                   8012:     my ($allpathcond) = @_;
                   8013:     my $result=0;
                   8014:     if ($env{'request.course.id'}
                   8015: 	&& defined($allpathcond)) {
                   8016: 	my $operand='|';
                   8017: 	my @stack;
                   8018: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8019: 	    if ($chunk eq '(') {
                   8020: 		push @stack,($operand,$result);
                   8021: 	    } elsif ($chunk eq ')') {
                   8022: 		my $before=pop @stack;
                   8023: 		if (pop @stack eq '&') {
                   8024: 		    $result=$result>$before?$before:$result;
                   8025: 		} else {
                   8026: 		    $result=$result>$before?$result:$before;
                   8027: 		}
                   8028: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8029: 		$operand=$chunk;
                   8030: 	    } else {
                   8031: 		my $new=directcondval($chunk);
                   8032: 		if ($operand eq '&') {
                   8033: 		    $result=$result>$new?$new:$result;
                   8034: 		} else {
                   8035: 		    $result=$result>$new?$result:$new;
                   8036: 		}
                   8037: 	    }
                   8038: 	}
1.26      www      8039:     }
                   8040:     return $result;
1.421     albertel 8041: }
                   8042: 
                   8043: # ---------------------------------------------------- Devalidate courseresdata
                   8044: 
                   8045: sub devalidatecourseresdata {
                   8046:     my ($coursenum,$coursedomain)=@_;
                   8047:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8048:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8049: }
                   8050: 
1.763     www      8051: 
1.200     www      8052: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8053: #
                   8054: #  Parameters:
                   8055: #      $coursenum    - Number of the course.
                   8056: #      $coursedomain - Domain at which the course was created.
                   8057: #  Returns:
                   8058: #     A hash of the course parameters along (I think) with timestamps
                   8059: #     and version info.
1.877     foxr     8060: 
1.624     albertel 8061: sub get_courseresdata {
                   8062:     my ($coursenum,$coursedomain)=@_;
1.200     www      8063:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8064:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8065:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8066:     my %dumpreply;
1.417     albertel 8067:     unless (defined($cached)) {
1.624     albertel 8068: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8069: 	$result=\%dumpreply;
1.251     albertel 8070: 	my ($tmp) = keys(%dumpreply);
                   8071: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8072: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8073: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8074: 	    return $tmp;
1.416     albertel 8075: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8076: 	    $result=undef;
1.599     albertel 8077: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8078: 	}
                   8079:     }
1.624     albertel 8080:     return $result;
                   8081: }
                   8082: 
1.633     albertel 8083: sub devalidateuserresdata {
                   8084:     my ($uname,$udom)=@_;
                   8085:     my $hashid="$udom:$uname";
                   8086:     &devalidate_cache_new('userres',$hashid);
                   8087: }
                   8088: 
1.624     albertel 8089: sub get_userresdata {
                   8090:     my ($uname,$udom)=@_;
                   8091:     #most student don\'t have any data set, check if there is some data
                   8092:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8093: 
                   8094:     my $hashid="$udom:$uname";
                   8095:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8096:     if (!defined($cached)) {
                   8097: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8098: 	$result=\%resourcedata;
                   8099: 	&do_cache_new('userres',$hashid,$result,600);
                   8100:     }
                   8101:     my ($tmp)=keys(%$result);
                   8102:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8103: 	return $result;
                   8104:     }
                   8105:     #error 2 occurs when the .db doesn't exist
                   8106:     if ($tmp!~/error: 2 /) {
1.672     albertel 8107: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8108: 		 " Trying to get resource data for ".
                   8109: 		 $uname." at ".$udom.": ".
                   8110: 		 $tmp."</font>");
                   8111:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8112: 	#&EXT_cache_set($udom,$uname);
                   8113: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8114: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8115:     }
                   8116:     return $tmp;
                   8117: }
1.879     foxr     8118: #----------------------------------------------- resdata - return resource data
                   8119: #  Purpose:
                   8120: #    Return resource data for either users or for a course.
                   8121: #  Parameters:
                   8122: #     $name      - Course/user name.
                   8123: #     $domain    - Name of the domain the user/course is registered on.
                   8124: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8125: #     @which     - Array of names of resources desired.
                   8126: #  Returns:
                   8127: #     The value of the first reasource in @which that is found in the
                   8128: #     resource hash.
                   8129: #  Exceptional Conditions:
                   8130: #     If the $type passed in is not valid (not the string 'course' or 
                   8131: #     'user', an undefined  reference is returned.
                   8132: #     If none of the resources are found, an undef is returned
1.624     albertel 8133: sub resdata {
                   8134:     my ($name,$domain,$type,@which)=@_;
                   8135:     my $result;
                   8136:     if ($type eq 'course') {
                   8137: 	$result=&get_courseresdata($name,$domain);
                   8138:     } elsif ($type eq 'user') {
                   8139: 	$result=&get_userresdata($name,$domain);
                   8140:     }
                   8141:     if (!ref($result)) { return $result; }    
1.251     albertel 8142:     foreach my $item (@which) {
1.927     albertel 8143: 	if (defined($result->{$item->[0]})) {
                   8144: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8145: 	}
1.250     albertel 8146:     }
1.291     albertel 8147:     return undef;
1.200     www      8148: }
                   8149: 
1.379     matthew  8150: #
                   8151: # EXT resource caching routines
                   8152: #
                   8153: 
                   8154: sub clear_EXT_cache_status {
1.383     albertel 8155:     &delenv('cache.EXT.');
1.379     matthew  8156: }
                   8157: 
                   8158: sub EXT_cache_status {
                   8159:     my ($target_domain,$target_user) = @_;
1.383     albertel 8160:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8161:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8162:         # We know already the user has no data
                   8163:         return 1;
                   8164:     } else {
                   8165:         return 0;
                   8166:     }
                   8167: }
                   8168: 
                   8169: sub EXT_cache_set {
                   8170:     my ($target_domain,$target_user) = @_;
1.383     albertel 8171:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8172:     #&appenv({$cachename => time});
1.379     matthew  8173: }
                   8174: 
1.28      www      8175: # --------------------------------------------------------- Value of a Variable
1.58      www      8176: sub EXT {
1.715     albertel 8177: 
1.395     albertel 8178:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8179:     unless ($varname) { return ''; }
1.218     albertel 8180:     #get real user name/domain, courseid and symb
                   8181:     my $courseid;
1.359     albertel 8182:     my $publicuser;
1.427     www      8183:     if ($symbparm) {
                   8184: 	$symbparm=&get_symb_from_alias($symbparm);
                   8185:     }
1.218     albertel 8186:     if (!($uname && $udom)) {
1.790     albertel 8187:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8188:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8189:     } else {
1.620     albertel 8190: 	$courseid=$env{'request.course.id'};
1.218     albertel 8191:     }
1.48      www      8192:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8193:     my $rest;
1.320     albertel 8194:     if (defined($therest[0])) {
1.48      www      8195:        $rest=join('.',@therest);
                   8196:     } else {
                   8197:        $rest='';
                   8198:     }
1.320     albertel 8199: 
1.57      www      8200:     my $qualifierrest=$qualifier;
                   8201:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8202:     my $spacequalifierrest=$space;
                   8203:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8204:     if ($realm eq 'user') {
1.48      www      8205: # --------------------------------------------------------------- user.resource
                   8206: 	if ($space eq 'resource') {
1.651     albertel 8207: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8208: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8209: 		 &&
1.744     albertel 8210: 		 ($symbparm eq &symbread()) ) {	
                   8211: 		# if we are in the middle of processing the resource the
                   8212: 		# get the value we are planning on committing
                   8213:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8214:                     return $Apache::lonhomework::results{$qualifierrest};
                   8215:                 } else {
                   8216:                     return $Apache::lonhomework::history{$qualifierrest};
                   8217:                 }
1.335     albertel 8218: 	    } else {
1.359     albertel 8219: 		my %restored;
1.620     albertel 8220: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8221: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8222: 		} else {
                   8223: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8224: 		}
1.335     albertel 8225: 		return $restored{$qualifierrest};
                   8226: 	    }
1.48      www      8227: # ----------------------------------------------------------------- user.access
                   8228:         } elsif ($space eq 'access') {
1.218     albertel 8229: 	    # FIXME - not supporting calls for a specific user
1.48      www      8230:             return &allowed($qualifier,$rest);
                   8231: # ------------------------------------------ user.preferences, user.environment
                   8232:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8233: 	    if (($uname eq $env{'user.name'}) &&
                   8234: 		($udom eq $env{'user.domain'})) {
                   8235: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8236: 	    } else {
1.359     albertel 8237: 		my %returnhash;
                   8238: 		if (!$publicuser) {
                   8239: 		    %returnhash=&userenvironment($udom,$uname,
                   8240: 						 $qualifierrest);
                   8241: 		}
1.218     albertel 8242: 		return $returnhash{$qualifierrest};
                   8243: 	    }
1.48      www      8244: # ----------------------------------------------------------------- user.course
                   8245:         } elsif ($space eq 'course') {
1.218     albertel 8246: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8247:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8248: # ------------------------------------------------------------------- user.role
                   8249:         } elsif ($space eq 'role') {
1.218     albertel 8250: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8251:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8252:             if ($qualifier eq 'value') {
                   8253: 		return $role;
                   8254:             } elsif ($qualifier eq 'extent') {
                   8255:                 return $where;
                   8256:             }
                   8257: # ----------------------------------------------------------------- user.domain
                   8258:         } elsif ($space eq 'domain') {
1.218     albertel 8259:             return $udom;
1.48      www      8260: # ------------------------------------------------------------------- user.name
                   8261:         } elsif ($space eq 'name') {
1.218     albertel 8262:             return $uname;
1.48      www      8263: # ---------------------------------------------------- Any other user namespace
1.29      www      8264:         } else {
1.359     albertel 8265: 	    my %reply;
                   8266: 	    if (!$publicuser) {
                   8267: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8268: 	    }
                   8269: 	    return $reply{$qualifierrest};
1.48      www      8270:         }
1.236     www      8271:     } elsif ($realm eq 'query') {
                   8272: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8273:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8274: 						[$spacequalifierrest]);
1.620     albertel 8275: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8276:    } elsif ($realm eq 'request') {
1.48      www      8277: # ------------------------------------------------------------- request.browser
                   8278:         if ($space eq 'browser') {
1.430     www      8279: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8280: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8281: 		    return 1;
                   8282: 		} else {
                   8283: 		    return 0;
                   8284: 		}
                   8285: 	    } else {
1.620     albertel 8286: 		return $env{'browser.'.$qualifier};
1.430     www      8287: 	    }
1.57      www      8288: # ------------------------------------------------------------ request.filename
                   8289:         } else {
1.620     albertel 8290:             return $env{'request.'.$spacequalifierrest};
1.29      www      8291:         }
1.28      www      8292:     } elsif ($realm eq 'course') {
1.48      www      8293: # ---------------------------------------------------------- course.description
1.620     albertel 8294:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8295:     } elsif ($realm eq 'resource') {
1.165     www      8296: 
1.620     albertel 8297: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8298: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8299: 	}
1.693     albertel 8300: 
                   8301: 	if ($space eq 'title') {
                   8302: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8303: 	    return &gettitle($symbparm);
                   8304: 	}
                   8305: 	
                   8306: 	if ($space eq 'map') {
                   8307: 	    my ($map) = &decode_symb($symbparm);
                   8308: 	    return &symbread($map);
                   8309: 	}
1.905     albertel 8310: 	if ($space eq 'filename') {
                   8311: 	    if ($symbparm) {
                   8312: 		return &clutter((&decode_symb($symbparm))[2]);
                   8313: 	    }
                   8314: 	    return &hreflocation('',$env{'request.filename'});
                   8315: 	}
1.693     albertel 8316: 
                   8317: 	my ($section, $group, @groups);
1.593     albertel 8318: 	my ($courselevelm,$courselevel);
1.539     albertel 8319: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8320: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8321: 
1.218     albertel 8322: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8323: 
1.60      www      8324: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8325: 	    my $symbp=$symbparm;
1.735     albertel 8326: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8327: 
                   8328: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8329: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8330: 
1.620     albertel 8331: 	    if (($env{'user.name'} eq $uname) &&
                   8332: 		($env{'user.domain'} eq $udom)) {
                   8333: 		$section=$env{'request.course.sec'};
1.733     raeburn  8334:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8335:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8336: 	    } else {
1.539     albertel 8337: 		if (! defined($usection)) {
1.551     albertel 8338: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8339: 		} else {
                   8340: 		    $section = $usection;
                   8341: 		}
1.733     raeburn  8342:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8343: 	    }
                   8344: 
                   8345: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8346: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8347: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8348: 
1.593     albertel 8349: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8350: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8351: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8352: 
1.60      www      8353: # ----------------------------------------------------------- first, check user
1.624     albertel 8354: 
                   8355: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8356: 				       ([$courselevelr,'resource'],
                   8357: 					[$courselevelm,'map'     ],
                   8358: 					[$courselevel, 'course'  ]));
1.931     albertel 8359: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8360: 
1.594     albertel 8361: # ------------------------------------------------ second, check some of course
1.684     raeburn  8362:             my $coursereply;
1.691     raeburn  8363:             if (@groups > 0) {
                   8364:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8365:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8366:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8367:             }
1.96      www      8368: 
1.684     raeburn  8369: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8370: 				  $env{'course.'.$courseid.'.domain'},
                   8371: 				  'course',
                   8372: 				  ([$seclevelr,   'resource'],
                   8373: 				   [$seclevelm,   'map'     ],
                   8374: 				   [$seclevel,    'course'  ],
                   8375: 				   [$courselevelr,'resource']));
                   8376: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8377: 
1.60      www      8378: # ------------------------------------------------------ third, check map parms
1.218     albertel 8379: 	    my %parmhash=();
                   8380: 	    my $thisparm='';
                   8381: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8382: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8383: 		    &GDBM_READER(),0640)) {
1.218     albertel 8384: 		$thisparm=$parmhash{$symbparm};
                   8385: 		untie(%parmhash);
                   8386: 	    }
1.927     albertel 8387: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8388: 	}
1.594     albertel 8389: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8390: 
1.218     albertel 8391: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8392: 	my $filename;
                   8393: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8394: 	if ($symbparm) {
1.409     www      8395: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8396: 	} else {
1.620     albertel 8397: 	    $filename=$env{'request.filename'};
1.282     albertel 8398: 	}
                   8399: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8400: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8401: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8402: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8403: 
1.927     albertel 8404: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8405: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8406: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8407: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8408: 				     $env{'course.'.$courseid.'.domain'},
                   8409: 				     'course',
1.927     albertel 8410: 				     ([$courselevelm,'map'   ],
                   8411: 				      [$courselevel, 'course']));
                   8412: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8413: 	}
1.145     www      8414: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8415: 	unless ($space eq '0') {
1.336     albertel 8416: 	    my @parts=split(/_/,$space);
                   8417: 	    my $id=pop(@parts);
                   8418: 	    my $part=join('_',@parts);
                   8419: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8420: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8421: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8422: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8423: 	}
1.395     albertel 8424: 	if ($recurse) { return undef; }
                   8425: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8426: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8427: # ---------------------------------------------------- Any other user namespace
                   8428:     } elsif ($realm eq 'environment') {
                   8429: # ----------------------------------------------------------------- environment
1.620     albertel 8430: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8431: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8432: 	} else {
1.770     albertel 8433: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8434: 		return '';
                   8435: 	    }
1.219     albertel 8436: 	    my %returnhash=&userenvironment($udom,$uname,
                   8437: 					    $spacequalifierrest);
                   8438: 	    return $returnhash{$spacequalifierrest};
                   8439: 	}
1.28      www      8440:     } elsif ($realm eq 'system') {
1.48      www      8441: # ----------------------------------------------------------------- system.time
                   8442: 	if ($space eq 'time') {
                   8443: 	    return time;
                   8444:         }
1.696     albertel 8445:     } elsif ($realm eq 'server') {
                   8446: # ----------------------------------------------------------------- system.time
                   8447: 	if ($space eq 'name') {
                   8448: 	    return $ENV{'SERVER_NAME'};
                   8449:         }
1.28      www      8450:     }
1.48      www      8451:     return '';
1.61      www      8452: }
                   8453: 
1.927     albertel 8454: sub get_reply {
                   8455:     my ($reply_value) = @_;
1.940     raeburn  8456:     if (ref($reply_value) eq 'ARRAY') {
                   8457:         if (wantarray) {
                   8458: 	    return @$reply_value;
                   8459:         }
                   8460:         return $reply_value->[0];
                   8461:     } else {
                   8462:         return $reply_value;
1.927     albertel 8463:     }
                   8464: }
                   8465: 
1.691     raeburn  8466: sub check_group_parms {
                   8467:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8468:     my @groupitems = ();
                   8469:     my $resultitem;
1.927     albertel 8470:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8471:     foreach my $group (@{$groups}) {
                   8472:         foreach my $level (@levels) {
1.927     albertel 8473:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8474:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8475:         }
                   8476:     }
                   8477:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8478:                             $env{'course.'.$courseid.'.domain'},
                   8479:                                      'course',@groupitems);
                   8480:     return $coursereply;
                   8481: }
                   8482: 
                   8483: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8484:     my ($courseid,@groups) = @_;
                   8485:     @groups = sort(@groups);
1.691     raeburn  8486:     return @groups;
                   8487: }
                   8488: 
1.395     albertel 8489: sub packages_tab_default {
                   8490:     my ($uri,$varname)=@_;
                   8491:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8492: 
                   8493:     my (@extension,@specifics,$do_default);
                   8494:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8495: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8496: 	if ($pack_type eq 'default') {
                   8497: 	    $do_default=1;
                   8498: 	} elsif ($pack_type eq 'extension') {
                   8499: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8500: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8501: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8502: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8503: 	}
                   8504:     }
                   8505:     # first look for a package that matches the requested part id
                   8506:     foreach my $package (@specifics) {
                   8507: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8508: 	next if ($pack_part ne $part);
                   8509: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8510: 	    return $packagetab{"$pack_type&$name&default"};
                   8511: 	}
                   8512:     }
                   8513:     # look for any possible matching non extension_ package
                   8514:     foreach my $package (@specifics) {
                   8515: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8516: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8517: 	    return $packagetab{"$pack_type&$name&default"};
                   8518: 	}
1.585     albertel 8519: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8520: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8521: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8522: 	}
                   8523:     }
1.738     albertel 8524:     # look for any posible extension_ match
                   8525:     foreach my $package (@extension) {
                   8526: 	my ($package,$pack_type)=@{$package};
                   8527: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8528: 	    return $packagetab{"$pack_type&$name&default"};
                   8529: 	}
                   8530: 	if (defined($packagetab{$package."&$name&default"})) {
                   8531: 	    return $packagetab{$package."&$name&default"};
                   8532: 	}
                   8533:     }
                   8534:     # look for a global default setting
                   8535:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8536: 	return $packagetab{"default&$name&default"};
                   8537:     }
1.395     albertel 8538:     return undef;
                   8539: }
                   8540: 
1.334     albertel 8541: sub add_prefix_and_part {
                   8542:     my ($prefix,$part)=@_;
                   8543:     my $keyroot;
                   8544:     if (defined($prefix) && $prefix !~ /^__/) {
                   8545: 	# prefix that has a part already
                   8546: 	$keyroot=$prefix;
                   8547:     } elsif (defined($prefix)) {
                   8548: 	# prefix that is missing a part
                   8549: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8550:     } else {
                   8551: 	# no prefix at all
                   8552: 	if (defined($part)) { $keyroot='_'.$part; }
                   8553:     }
                   8554:     return $keyroot;
                   8555: }
                   8556: 
1.71      www      8557: # ---------------------------------------------------------------- Get metadata
                   8558: 
1.599     albertel 8559: my %metaentry;
1.71      www      8560: sub metadata {
1.176     www      8561:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8562:     $uri=&declutter($uri);
1.288     albertel 8563:     # if it is a non metadata possible uri return quickly
1.529     albertel 8564:     if (($uri eq '') || 
                   8565: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8566: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.13  raeburn  8567:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^\*uploaded\/.+\.sequence$/) ) {
1.924     albertel 8568: 	return undef;
                   8569:     }
                   8570:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8571: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8572: 	return undef;
1.288     albertel 8573:     }
1.73      www      8574:     my $filename=$uri;
                   8575:     $uri=~s/\.meta$//;
1.172     www      8576: #
                   8577: # Is the metadata already cached?
1.177     www      8578: # Look at timestamp of caching
1.172     www      8579: # Everything is cached by the main uri, libraries are never directly cached
                   8580: #
1.428     albertel 8581:     if (!defined($liburi)) {
1.599     albertel 8582: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8583: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8584:     }
                   8585:     {
1.172     www      8586: #
                   8587: # Is this a recursive call for a library?
                   8588: #
1.599     albertel 8589: #	if (! exists($metacache{$uri})) {
                   8590: #	    $metacache{$uri}={};
                   8591: #	}
1.924     albertel 8592: 	my $cachetime = 60*60;
1.171     www      8593:         if ($liburi) {
                   8594: 	    $liburi=&declutter($liburi);
                   8595:             $filename=$liburi;
1.401     bowersj2 8596:         } else {
1.599     albertel 8597: 	    &devalidate_cache_new('meta',$uri);
                   8598: 	    undef(%metaentry);
1.401     bowersj2 8599: 	}
1.140     www      8600:         my %metathesekeys=();
1.73      www      8601:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8602: 	my $metastring;
1.924     albertel 8603: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8604: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8605: 	    $metastring = 
1.929     albertel 8606: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8607: 					  ('grade_target' => 'meta'));
                   8608: 	    $cachetime = 1; # only want this cached in the child not long term
                   8609: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8610: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8611: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8612: 	    $metastring=&getfile($file);
1.489     albertel 8613: 	}
1.208     albertel 8614:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8615:         my $token;
1.140     www      8616:         undef %metathesekeys;
1.71      www      8617:         while ($token=$parser->get_token) {
1.339     albertel 8618: 	    if ($token->[0] eq 'S') {
                   8619: 		if (defined($token->[2]->{'package'})) {
1.172     www      8620: #
                   8621: # This is a package - get package info
                   8622: #
1.339     albertel 8623: 		    my $package=$token->[2]->{'package'};
                   8624: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8625: 		    if (defined($token->[2]->{'id'})) { 
                   8626: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8627: 		    }
1.599     albertel 8628: 		    if ($metaentry{':packages'}) {
                   8629: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8630: 		    } else {
1.599     albertel 8631: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8632: 		    }
1.736     albertel 8633: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8634: 			my $part=$keyroot;
                   8635: 			$part=~s/^\_//;
1.736     albertel 8636: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8637: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8638: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8639: 			    # ignore package.tab specified default values
                   8640:                             # here &package_tab_default() will fetch those
                   8641: 			    if ($subp eq 'default') { next; }
1.736     albertel 8642: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8643: 			    my $unikey;
                   8644: 			    if ($pack =~ /_0$/) {
                   8645: 				$unikey='parameter_0_'.$name;
                   8646: 				$part=0;
                   8647: 			    } else {
                   8648: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8649: 			    }
1.339     albertel 8650: 			    if ($subp eq 'display') {
                   8651: 				$value.=' [Part: '.$part.']';
                   8652: 			    }
1.599     albertel 8653: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8654: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8655: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8656: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8657: 			    }
1.599     albertel 8658: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8659: 				$metaentry{':'.$unikey}=
                   8660: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8661: 			    }
1.339     albertel 8662: 			}
                   8663: 		    }
                   8664: 		} else {
1.172     www      8665: #
                   8666: # This is not a package - some other kind of start tag
1.339     albertel 8667: #
                   8668: 		    my $entry=$token->[1];
                   8669: 		    my $unikey;
                   8670: 		    if ($entry eq 'import') {
                   8671: 			$unikey='';
                   8672: 		    } else {
                   8673: 			$unikey=$entry;
                   8674: 		    }
                   8675: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8676: 
                   8677: 		    if (defined($token->[2]->{'id'})) { 
                   8678: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8679: 		    }
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: #
                   8685: 			if ($depthcount<20) {
                   8686: 			    my $location=$parser->get_text('/import');
                   8687: 			    my $dir=$filename;
                   8688: 			    $dir=~s|[^/]*$||;
                   8689: 			    $location=&filelocation($dir,$location);
1.736     albertel 8690: 			    my $metadata = 
                   8691: 				&metadata($uri,'keys', $location,$unikey,
                   8692: 					  $depthcount+1);
                   8693: 			    foreach my $meta (split(',',$metadata)) {
                   8694: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8695: 				$metathesekeys{$meta}=1;
1.339     albertel 8696: 			    }
                   8697: 			}
                   8698: 		    } else { 
                   8699: 			if (defined($token->[2]->{'name'})) { 
                   8700: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8701: 			}
                   8702: 			$metathesekeys{$unikey}=1;
1.736     albertel 8703: 			foreach my $param (@{$token->[3]}) {
                   8704: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8705: 				$token->[2]->{$param};
1.339     albertel 8706: 			}
                   8707: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8708: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8709: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8710: 		 # only ws inside the tag, and not in default, so use default
                   8711: 		 # as value
1.599     albertel 8712: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8713: 			} elsif ( $internaltext =~ /\S/ ) {
                   8714: 		  # something interesting inside the tag
                   8715: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8716: 			} else {
1.908     albertel 8717: 		  # no interesting values, don't set a default
1.339     albertel 8718: 			}
1.172     www      8719: # end of not-a-package not-a-library import
1.339     albertel 8720: 		    }
1.172     www      8721: # end of not-a-package start tag
1.339     albertel 8722: 		}
1.172     www      8723: # the next is the end of "start tag"
1.339     albertel 8724: 	    }
                   8725: 	}
1.483     albertel 8726: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8727: 	$extension = lc($extension);
                   8728: 	if ($extension eq 'htm') { $extension='html'; }
                   8729: 
1.737     albertel 8730: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8731: 	    #no specific packages #how's our extension
                   8732: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8733: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8734: 					 \%metathesekeys);
                   8735: 	}
1.883     albertel 8736: 
                   8737: 	if (!exists($metaentry{':packages'})
                   8738: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8739: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8740: 		#no specific packages well let's get default then
                   8741: 		if ($key!~/^default&/) { next; }
1.488     albertel 8742: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8743: 					     \%metathesekeys);
                   8744: 	    }
                   8745: 	}
1.338     www      8746: # are there custom rights to evaluate
1.599     albertel 8747: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8748: 
1.338     www      8749:     #
                   8750:     # Importing a rights file here
1.339     albertel 8751:     #
                   8752: 	    unless ($depthcount) {
1.599     albertel 8753: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8754: 		my $dir=$filename;
                   8755: 		$dir=~s|[^/]*$||;
                   8756: 		$location=&filelocation($dir,$location);
1.736     albertel 8757: 		my $rights_metadata =
                   8758: 		    &metadata($uri,'keys',$location,'_rights',
                   8759: 			      $depthcount+1);
                   8760: 		foreach my $rights (split(',',$rights_metadata)) {
                   8761: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8762: 		    $metathesekeys{$rights}=1;
1.339     albertel 8763: 		}
                   8764: 	    }
                   8765: 	}
1.737     albertel 8766: 	# uniqifiy package listing
                   8767: 	my %seen;
                   8768: 	my @uniq_packages =
                   8769: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8770: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8771: 
                   8772: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8773: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8774: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8775: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8776: # this is the end of "was not already recently cached
1.71      www      8777:     }
1.599     albertel 8778:     return $metaentry{':'.$what};
1.261     albertel 8779: }
                   8780: 
1.488     albertel 8781: sub metadata_create_package_def {
1.483     albertel 8782:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8783:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8784:     if ($subp eq 'default') { next; }
                   8785:     
1.599     albertel 8786:     if (defined($metaentry{':packages'})) {
                   8787: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8788:     } else {
1.599     albertel 8789: 	$metaentry{':packages'}=$package;
1.483     albertel 8790:     }
                   8791:     my $value=$packagetab{$key};
                   8792:     my $unikey;
                   8793:     $unikey='parameter_0_'.$name;
1.599     albertel 8794:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8795:     $$metathesekeys{$unikey}=1;
1.599     albertel 8796:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8797: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8798:     }
1.599     albertel 8799:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8800: 	$metaentry{':'.$unikey}=
                   8801: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8802:     }
                   8803: }
                   8804: 
1.261     albertel 8805: sub metadata_generate_part0 {
                   8806:     my ($metadata,$metacache,$uri) = @_;
                   8807:     my %allnames;
1.737     albertel 8808:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8809: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8810: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8811: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8812: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8813: 	    $allnames{$name}=$part;
                   8814: 	  }
                   8815: 	}
                   8816:     }
                   8817:     foreach my $name (keys(%allnames)) {
                   8818:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8819:       my $key=":parameter_0_$name";
1.261     albertel 8820:       $$metacache{"$key.part"}='0';
                   8821:       $$metacache{"$key.name"}=$name;
1.428     albertel 8822:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8823: 					   $allnames{$name}.'_'.$name.
                   8824: 					   '.type'};
1.428     albertel 8825:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8826: 			     '.display'};
1.644     www      8827:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8828:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8829:       $$metacache{"$key.display"}=$olddis;
                   8830:     }
1.71      www      8831: }
                   8832: 
1.764     albertel 8833: # ------------------------------------------------------ Devalidate title cache
                   8834: 
                   8835: sub devalidate_title_cache {
                   8836:     my ($url)=@_;
                   8837:     if (!$env{'request.course.id'}) { return; }
                   8838:     my $symb=&symbread($url);
                   8839:     if (!$symb) { return; }
                   8840:     my $key=$env{'request.course.id'}."\0".$symb;
                   8841:     &devalidate_cache_new('title',$key);
                   8842: }
                   8843: 
1.1014    droeschl 8844: # ------------------------------------------------- Get the title of a course
                   8845: 
                   8846: sub current_course_title {
                   8847:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8848: }
1.301     www      8849: # ------------------------------------------------- Get the title of a resource
                   8850: 
                   8851: sub gettitle {
                   8852:     my $urlsymb=shift;
                   8853:     my $symb=&symbread($urlsymb);
1.534     albertel 8854:     if ($symb) {
1.620     albertel 8855: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8856: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8857: 	if (defined($cached)) { 
                   8858: 	    return $result;
                   8859: 	}
1.534     albertel 8860: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8861: 	my $title='';
1.907     albertel 8862: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8863: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8864: 	} else {
                   8865: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8866: 		    &GDBM_READER(),0640)) {
                   8867: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8868: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8869: 		untie(%bighash);
                   8870: 	    }
1.534     albertel 8871: 	}
                   8872: 	$title=~s/\&colon\;/\:/gs;
                   8873: 	if ($title) {
1.599     albertel 8874: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8875: 	}
                   8876: 	$urlsymb=$url;
                   8877:     }
                   8878:     my $title=&metadata($urlsymb,'title');
                   8879:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8880:     return $title;
1.301     www      8881: }
1.613     albertel 8882: 
1.614     albertel 8883: sub get_slot {
                   8884:     my ($which,$cnum,$cdom)=@_;
                   8885:     if (!$cnum || !$cdom) {
1.790     albertel 8886: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8887: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8888: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8889:     }
1.703     albertel 8890:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8891:     my %slotinfo;
                   8892:     if (exists($remembered{$key})) {
                   8893: 	$slotinfo{$which} = $remembered{$key};
                   8894:     } else {
                   8895: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8896: 	&Apache::lonhomework::showhash(%slotinfo);
                   8897: 	my ($tmp)=keys(%slotinfo);
                   8898: 	if ($tmp=~/^error:/) { return (); }
                   8899: 	$remembered{$key} = $slotinfo{$which};
                   8900:     }
1.616     albertel 8901:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8902: 	return %{$slotinfo{$which}};
                   8903:     }
                   8904:     return $slotinfo{$which};
1.614     albertel 8905: }
1.31      www      8906: # ------------------------------------------------- Update symbolic store links
                   8907: 
                   8908: sub symblist {
                   8909:     my ($mapname,%newhash)=@_;
1.438     www      8910:     $mapname=&deversion(&declutter($mapname));
1.31      www      8911:     my %hash;
1.620     albertel 8912:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8913:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8914:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8915: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8916: 		next if ($url eq 'last_known'
                   8917: 			 && $env{'form.no_update_last_known'});
                   8918: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8919: 						    $newhash{$url}->[1],
                   8920: 						    $newhash{$url}->[0]);
1.191     harris41 8921:             }
1.31      www      8922:             if (untie(%hash)) {
                   8923: 		return 'ok';
                   8924:             }
                   8925:         }
                   8926:     }
                   8927:     return 'error';
1.212     www      8928: }
                   8929: 
                   8930: # --------------------------------------------------------------- Verify a symb
                   8931: 
                   8932: sub symbverify {
1.510     www      8933:     my ($symb,$thisurl)=@_;
                   8934:     my $thisfn=$thisurl;
1.439     www      8935:     $thisfn=&declutter($thisfn);
1.215     www      8936: # direct jump to resource in page or to a sequence - will construct own symbs
                   8937:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8938: # check URL part
1.409     www      8939:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8940: 
1.431     www      8941:     unless ($url eq $thisfn) { return 0; }
1.213     www      8942: 
1.216     www      8943:     $symb=&symbclean($symb);
1.510     www      8944:     $thisurl=&deversion($thisurl);
1.439     www      8945:     $thisfn=&deversion($thisfn);
1.213     www      8946: 
                   8947:     my %bighash;
                   8948:     my $okay=0;
1.431     www      8949: 
1.620     albertel 8950:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8951:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8952:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8953:             $thisurl =~ s/\?.+$//;
                   8954:         }
1.510     www      8955:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8956:         unless ($ids) { 
1.510     www      8957:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8958:         }
                   8959:         if ($ids) {
                   8960: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8961: 	    foreach my $id (split(/\,/,$ids)) {
                   8962: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8963:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8964:                    $symb =~ s/\?.+$//;
                   8965:                }
1.216     www      8966:                if (
                   8967:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8968:    eq $symb) { 
1.620     albertel 8969: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8970: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8971: 		       $okay=1; 
                   8972: 		   }
                   8973: 	       }
1.216     www      8974: 	   }
                   8975:         }
1.213     www      8976: 	untie(%bighash);
                   8977:     }
                   8978:     return $okay;
1.31      www      8979: }
                   8980: 
1.210     www      8981: # --------------------------------------------------------------- Clean-up symb
                   8982: 
                   8983: sub symbclean {
                   8984:     my $symb=shift;
1.568     albertel 8985:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8986: # remove version from map
                   8987:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8988: 
1.210     www      8989: # remove version from URL
                   8990:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8991: 
1.507     www      8992: # remove wrapper
                   8993: 
1.510     www      8994:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8995:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8996:     return $symb;
1.409     www      8997: }
                   8998: 
                   8999: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9000: 
                   9001: sub encode_symb {
                   9002:     my ($map,$resid,$url)=@_;
                   9003:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9004: }
1.409     www      9005: 
                   9006: sub decode_symb {
1.568     albertel 9007:     my $symb=shift;
                   9008:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9009:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9010:     return (&fixversion($map),$resid,&fixversion($url));
                   9011: }
                   9012: 
                   9013: sub fixversion {
                   9014:     my $fn=shift;
1.609     banghart 9015:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9016:     my %bighash;
                   9017:     my $uri=&clutter($fn);
1.620     albertel 9018:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9019: # is this cached?
1.599     albertel 9020:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9021:     if (defined($cached)) { return $result; }
                   9022: # unfortunately not cached, or expired
1.620     albertel 9023:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9024: 	    &GDBM_READER(),0640)) {
                   9025:  	if ($bighash{'version_'.$uri}) {
                   9026:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9027:  	    unless (($version eq 'mostrecent') || 
                   9028: 		    ($version==&getversion($uri))) {
1.440     www      9029:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9030:  	    }
                   9031:  	}
                   9032:  	untie %bighash;
1.413     www      9033:     }
1.599     albertel 9034:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9035: }
                   9036: 
                   9037: sub deversion {
                   9038:     my $url=shift;
                   9039:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9040:     return $url;
1.210     www      9041: }
                   9042: 
1.31      www      9043: # ------------------------------------------------------ Return symb list entry
                   9044: 
                   9045: sub symbread {
1.249     www      9046:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9047:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9048:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9049: # no filename provided? try from environment
1.44      www      9050:     unless ($thisfn) {
1.620     albertel 9051:         if ($env{'request.symb'}) {
                   9052: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9053: 	}
1.620     albertel 9054: 	$thisfn=$env{'request.filename'};
1.44      www      9055:     }
1.569     albertel 9056:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9057: # is that filename actually a symb? Verify, clean, and return
                   9058:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9059: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9060: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9061: 	}
1.242     www      9062:     }
1.44      www      9063:     $thisfn=declutter($thisfn);
1.31      www      9064:     my %hash;
1.37      www      9065:     my %bighash;
                   9066:     my $syval='';
1.620     albertel 9067:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9068:         my $targetfn = $thisfn;
1.609     banghart 9069:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9070:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9071:         }
1.687     albertel 9072: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9073: 	    $targetfn=$1;
                   9074: 	}
1.620     albertel 9075:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9076:                       &GDBM_READER(),0640)) {
1.481     raeburn  9077: 	    $syval=$hash{$targetfn};
1.37      www      9078:             untie(%hash);
                   9079:         }
                   9080: # ---------------------------------------------------------- There was an entry
                   9081:         if ($syval) {
1.601     albertel 9082: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9083: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9084: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9085: 		    #return $env{$cache_str}='';
1.601     albertel 9086: 		#}    
                   9087: 		#$syval.=$1;
                   9088: 	    #}
1.37      www      9089:         } else {
                   9090: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9091:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9092:                             &GDBM_READER(),0640)) {
1.37      www      9093: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9094:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9095:               unless ($ids) { 
                   9096:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9097:               }
                   9098:               unless ($ids) {
                   9099: # alias?
                   9100: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9101:               }
1.37      www      9102:               if ($ids) {
                   9103: # ------------------------------------------------------------------- Has ID(s)
                   9104:                  my @possibilities=split(/\,/,$ids);
1.39      www      9105:                  if ($#possibilities==0) {
                   9106: # ----------------------------------------------- There is only one possibility
1.37      www      9107: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9108: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9109: 						    $resid,$thisfn);
1.249     www      9110:                  } elsif (!$donotrecurse) {
1.39      www      9111: # ------------------------------------------ There is more than one possibility
                   9112:                      my $realpossible=0;
1.800     albertel 9113:                      foreach my $id (@possibilities) {
                   9114: 			 my $file=$bighash{'src_'.$id};
1.39      www      9115:                          if (&allowed('bre',$file)) {
1.800     albertel 9116:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9117:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9118: 				$realpossible++;
1.626     albertel 9119:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9120: 						    $resid,$thisfn);
1.39      www      9121:                             }
                   9122: 			 }
1.191     harris41 9123:                      }
1.39      www      9124: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9125:                  } else {
                   9126:                      $syval='';
1.37      www      9127:                  }
                   9128: 	      }
                   9129:               untie(%bighash)
1.481     raeburn  9130:            }
1.31      www      9131:         }
1.62      www      9132:         if ($syval) {
1.620     albertel 9133: 	    return $env{$cache_str}=$syval;
1.62      www      9134:         }
1.31      www      9135:     }
1.949     raeburn  9136:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9137:     return $env{$cache_str}='';
1.31      www      9138: }
                   9139: 
                   9140: # ---------------------------------------------------------- Return random seed
                   9141: 
1.32      www      9142: sub numval {
                   9143:     my $txt=shift;
                   9144:     $txt=~tr/A-J/0-9/;
                   9145:     $txt=~tr/a-j/0-9/;
                   9146:     $txt=~tr/K-T/0-9/;
                   9147:     $txt=~tr/k-t/0-9/;
                   9148:     $txt=~tr/U-Z/0-5/;
                   9149:     $txt=~tr/u-z/0-5/;
                   9150:     $txt=~s/\D//g;
1.564     albertel 9151:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9152:     return int($txt);
1.368     albertel 9153: }
                   9154: 
1.484     albertel 9155: sub numval2 {
                   9156:     my $txt=shift;
                   9157:     $txt=~tr/A-J/0-9/;
                   9158:     $txt=~tr/a-j/0-9/;
                   9159:     $txt=~tr/K-T/0-9/;
                   9160:     $txt=~tr/k-t/0-9/;
                   9161:     $txt=~tr/U-Z/0-5/;
                   9162:     $txt=~tr/u-z/0-5/;
                   9163:     $txt=~s/\D//g;
                   9164:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9165:     my $total;
                   9166:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9167:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9168:     return int($total);
                   9169: }
                   9170: 
1.575     albertel 9171: sub numval3 {
                   9172:     use integer;
                   9173:     my $txt=shift;
                   9174:     $txt=~tr/A-J/0-9/;
                   9175:     $txt=~tr/a-j/0-9/;
                   9176:     $txt=~tr/K-T/0-9/;
                   9177:     $txt=~tr/k-t/0-9/;
                   9178:     $txt=~tr/U-Z/0-5/;
                   9179:     $txt=~tr/u-z/0-5/;
                   9180:     $txt=~s/\D//g;
                   9181:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9182:     my $total;
                   9183:     foreach my $val (@txts) { $total+=$val; }
                   9184:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9185:     return $total;
                   9186: }
                   9187: 
1.675     albertel 9188: sub digest {
                   9189:     my ($data)=@_;
                   9190:     my $digest=&Digest::MD5::md5($data);
                   9191:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9192:     my ($e,$f);
                   9193:     {
                   9194:         use integer;
                   9195:         $e=($a+$b);
                   9196:         $f=($c+$d);
                   9197:         if ($_64bit) {
                   9198:             $e=(($e<<32)>>32);
                   9199:             $f=(($f<<32)>>32);
                   9200:         }
                   9201:     }
                   9202:     if (wantarray) {
                   9203: 	return ($e,$f);
                   9204:     } else {
                   9205: 	my $g;
                   9206: 	{
                   9207: 	    use integer;
                   9208: 	    $g=($e+$f);
                   9209: 	    if ($_64bit) {
                   9210: 		$g=(($g<<32)>>32);
                   9211: 	    }
                   9212: 	}
                   9213: 	return $g;
                   9214:     }
                   9215: }
                   9216: 
1.368     albertel 9217: sub latest_rnd_algorithm_id {
1.675     albertel 9218:     return '64bit5';
1.366     albertel 9219: }
1.32      www      9220: 
1.503     albertel 9221: sub get_rand_alg {
                   9222:     my ($courseid)=@_;
1.790     albertel 9223:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9224:     if ($courseid) {
1.620     albertel 9225: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9226:     }
                   9227:     return &latest_rnd_algorithm_id();
                   9228: }
                   9229: 
1.562     albertel 9230: sub validCODE {
                   9231:     my ($CODE)=@_;
                   9232:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9233:     return 0;
                   9234: }
                   9235: 
1.491     albertel 9236: sub getCODE {
1.620     albertel 9237:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9238:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9239: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9240: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9241: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9242:     }
                   9243:     return undef;
                   9244: }
                   9245: 
1.31      www      9246: sub rndseed {
1.155     albertel 9247:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9248:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9249:     if (!defined($symb)) {
1.366     albertel 9250: 	unless ($symb=$wsymb) { return time; }
                   9251:     }
                   9252:     if (!$courseid) { $courseid=$wcourseid; }
                   9253:     if (!$domain) { $domain=$wdomain; }
                   9254:     if (!$username) { $username=$wusername }
1.503     albertel 9255:     my $which=&get_rand_alg();
1.803     albertel 9256: 
1.491     albertel 9257:     if (defined(&getCODE())) {
1.675     albertel 9258: 	if ($which eq '64bit5') {
                   9259: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9260: 	} elsif ($which eq '64bit4') {
1.575     albertel 9261: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9262: 	} else {
                   9263: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9264: 	}
1.675     albertel 9265:     } elsif ($which eq '64bit5') {
                   9266: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9267:     } elsif ($which eq '64bit4') {
                   9268: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9269:     } elsif ($which eq '64bit3') {
                   9270: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9271:     } elsif ($which eq '64bit2') {
                   9272: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9273:     } elsif ($which eq '64bit') {
                   9274: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9275:     }
                   9276:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9277: }
                   9278: 
                   9279: sub rndseed_32bit {
                   9280:     my ($symb,$courseid,$domain,$username)=@_;
                   9281:     {
                   9282: 	use integer;
                   9283: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9284: 	my $symbseed=numval($symb) << 22;
                   9285: 	my $namechck=unpack("%32C*",$username) << 17;
                   9286: 	my $nameseed=numval($username) << 12;
                   9287: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9288: 	my $courseseed=unpack("%32C*",$courseid);
                   9289: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9290: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9291: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9292: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9293: 	return $num;
                   9294:     }
                   9295: }
                   9296: 
                   9297: sub rndseed_64bit {
                   9298:     my ($symb,$courseid,$domain,$username)=@_;
                   9299:     {
                   9300: 	use integer;
                   9301: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9302: 	my $symbseed=numval($symb) << 10;
                   9303: 	my $namechck=unpack("%32S*",$username);
                   9304: 	
                   9305: 	my $nameseed=numval($username) << 21;
                   9306: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9307: 	my $courseseed=unpack("%32S*",$courseid);
                   9308: 	
                   9309: 	my $num1=$symbchck+$symbseed+$namechck;
                   9310: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9311: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9312: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9313: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9314: 	return "$num1,$num2";
1.155     albertel 9315:     }
1.366     albertel 9316: }
                   9317: 
1.443     albertel 9318: sub rndseed_64bit2 {
                   9319:     my ($symb,$courseid,$domain,$username)=@_;
                   9320:     {
                   9321: 	use integer;
                   9322: 	# strings need to be an even # of cahracters long, it it is odd the
                   9323:         # last characters gets thrown away
                   9324: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9325: 	my $symbseed=numval($symb) << 10;
                   9326: 	my $namechck=unpack("%32S*",$username.' ');
                   9327: 	
                   9328: 	my $nameseed=numval($username) << 21;
1.501     albertel 9329: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9330: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9331: 	
                   9332: 	my $num1=$symbchck+$symbseed+$namechck;
                   9333: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9334: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9335: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9336: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9337: 	return "$num1,$num2";
                   9338:     }
                   9339: }
                   9340: 
                   9341: sub rndseed_64bit3 {
                   9342:     my ($symb,$courseid,$domain,$username)=@_;
                   9343:     {
                   9344: 	use integer;
                   9345: 	# strings need to be an even # of cahracters long, it it is odd the
                   9346:         # last characters gets thrown away
                   9347: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9348: 	my $symbseed=numval2($symb) << 10;
                   9349: 	my $namechck=unpack("%32S*",$username.' ');
                   9350: 	
                   9351: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9352: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9353: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9354: 	
                   9355: 	my $num1=$symbchck+$symbseed+$namechck;
                   9356: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9357: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9358: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9359: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9360: 	
1.503     albertel 9361: 	return "$num1:$num2";
1.443     albertel 9362:     }
                   9363: }
                   9364: 
1.575     albertel 9365: sub rndseed_64bit4 {
                   9366:     my ($symb,$courseid,$domain,$username)=@_;
                   9367:     {
                   9368: 	use integer;
                   9369: 	# strings need to be an even # of cahracters long, it it is odd the
                   9370:         # last characters gets thrown away
                   9371: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9372: 	my $symbseed=numval3($symb) << 10;
                   9373: 	my $namechck=unpack("%32S*",$username.' ');
                   9374: 	
                   9375: 	my $nameseed=numval3($username) << 21;
                   9376: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9377: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9378: 	
                   9379: 	my $num1=$symbchck+$symbseed+$namechck;
                   9380: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9381: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9382: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9383: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9384: 	
                   9385: 	return "$num1:$num2";
                   9386:     }
                   9387: }
                   9388: 
1.675     albertel 9389: sub rndseed_64bit5 {
                   9390:     my ($symb,$courseid,$domain,$username)=@_;
                   9391:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9392:     return "$num1:$num2";
                   9393: }
                   9394: 
1.366     albertel 9395: sub rndseed_CODE_64bit {
                   9396:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9397:     {
1.366     albertel 9398: 	use integer;
1.443     albertel 9399: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9400: 	my $symbseed=numval2($symb);
1.491     albertel 9401: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9402: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9403: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9404: 	my $num1=$symbseed+$CODEchck;
                   9405: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9406: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9407: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9408: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9409: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9410: 	return "$num1:$num2";
1.366     albertel 9411:     }
                   9412: }
                   9413: 
1.575     albertel 9414: sub rndseed_CODE_64bit4 {
                   9415:     my ($symb,$courseid,$domain,$username)=@_;
                   9416:     {
                   9417: 	use integer;
                   9418: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9419: 	my $symbseed=numval3($symb);
                   9420: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9421: 	my $CODEseed=numval3(&getCODE());
                   9422: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9423: 	my $num1=$symbseed+$CODEchck;
                   9424: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9425: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9426: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9427: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9428: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9429: 	return "$num1:$num2";
                   9430:     }
                   9431: }
                   9432: 
1.675     albertel 9433: sub rndseed_CODE_64bit5 {
                   9434:     my ($symb,$courseid,$domain,$username)=@_;
                   9435:     my $code = &getCODE();
                   9436:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9437:     return "$num1:$num2";
                   9438: }
                   9439: 
1.366     albertel 9440: sub setup_random_from_rndseed {
                   9441:     my ($rndseed)=@_;
1.503     albertel 9442:     if ($rndseed =~/([,:])/) {
                   9443: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9444: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9445:     } else {
                   9446: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9447:     }
1.36      albertel 9448: }
                   9449: 
1.474     albertel 9450: sub latest_receipt_algorithm_id {
1.835     albertel 9451:     return 'receipt3';
1.474     albertel 9452: }
                   9453: 
1.480     www      9454: sub recunique {
                   9455:     my $fucourseid=shift;
                   9456:     my $unique;
1.835     albertel 9457:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9458: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9459: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9460:     } else {
                   9461: 	$unique=$perlvar{'lonReceipt'};
                   9462:     }
                   9463:     return unpack("%32C*",$unique);
                   9464: }
                   9465: 
                   9466: sub recprefix {
                   9467:     my $fucourseid=shift;
                   9468:     my $prefix;
1.835     albertel 9469:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9470: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9471: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9472:     } else {
                   9473: 	$prefix=$perlvar{'lonHostID'};
                   9474:     }
                   9475:     return unpack("%32C*",$prefix);
                   9476: }
                   9477: 
1.76      www      9478: sub ireceipt {
1.474     albertel 9479:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9480: 
                   9481:     my $return =&recprefix($fucourseid).'-';
                   9482: 
                   9483:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9484: 	$env{'request.state'} eq 'construct') {
                   9485: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9486: 	return $return;
                   9487:     }
                   9488: 
1.76      www      9489:     my $cuname=unpack("%32C*",$funame);
                   9490:     my $cudom=unpack("%32C*",$fudom);
                   9491:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9492:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9493:     my $cunique=&recunique($fucourseid);
1.474     albertel 9494:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9495:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9496: 
1.790     albertel 9497: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9498: 			       
                   9499: 	$return.= ($cunique%$cuname+
                   9500: 		   $cunique%$cudom+
                   9501: 		   $cusymb%$cuname+
                   9502: 		   $cusymb%$cudom+
                   9503: 		   $cucourseid%$cuname+
                   9504: 		   $cucourseid%$cudom+
                   9505: 		   $cpart%$cuname+
                   9506: 		   $cpart%$cudom);
                   9507:     } else {
                   9508: 	$return.= ($cunique%$cuname+
                   9509: 		   $cunique%$cudom+
                   9510: 		   $cusymb%$cuname+
                   9511: 		   $cusymb%$cudom+
                   9512: 		   $cucourseid%$cuname+
                   9513: 		   $cucourseid%$cudom);
                   9514:     }
                   9515:     return $return;
1.76      www      9516: }
                   9517: 
                   9518: sub receipt {
1.474     albertel 9519:     my ($part)=@_;
1.790     albertel 9520:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9521:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9522: }
1.260     ng       9523: 
1.790     albertel 9524: sub whichuser {
                   9525:     my ($passedsymb)=@_;
                   9526:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9527:     if (defined($env{'form.grade_symb'})) {
                   9528: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9529: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9530: 	if (!$allowed &&
                   9531: 	    exists($env{'request.course.sec'}) &&
                   9532: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9533: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9534: 			      '/'.$env{'request.course.sec'});
                   9535: 	}
                   9536: 	if ($allowed) {
                   9537: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9538: 	    $courseid=$tmp_courseid;
                   9539: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9540: 	    ($name)=&get_env_multiple('form.grade_username');
                   9541: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9542: 	}
                   9543:     }
                   9544:     if (!$passedsymb) {
                   9545: 	$symb=&symbread();
                   9546:     } else {
                   9547: 	$symb=$passedsymb;
                   9548:     }
                   9549:     $courseid=$env{'request.course.id'};
                   9550:     $domain=$env{'user.domain'};
                   9551:     $name=$env{'user.name'};
                   9552:     if ($name eq 'public' && $domain eq 'public') {
                   9553: 	if (!defined($env{'form.username'})) {
                   9554: 	    $env{'form.username'}.=time.rand(10000000);
                   9555: 	}
                   9556: 	$name.=$env{'form.username'};
                   9557:     }
                   9558:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9559: 
                   9560: }
                   9561: 
1.36      albertel 9562: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9563: # returns either the contents of the file or 
                   9564: # -1 if the file doesn't exist
1.481     raeburn  9565: #
                   9566: # if the target is a file that was uploaded via DOCS, 
                   9567: # a check will be made to see if a current copy exists on the local server,
                   9568: # if it does this will be served, otherwise a copy will be retrieved from
                   9569: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9570: # the local server.   
1.472     albertel 9571: 
1.36      albertel 9572: sub getfile {
1.538     albertel 9573:     my ($file) = @_;
1.609     banghart 9574:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9575:     &repcopy($file);
                   9576:     return &readfile($file);
                   9577: }
                   9578: 
                   9579: sub repcopy_userfile {
                   9580:     my ($file)=@_;
1.609     banghart 9581:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9582:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9583:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9584: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9585:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9586:     if (-e "$file") {
1.828     www      9587: # we already have a local copy, check it out
1.538     albertel 9588: 	my @fileinfo = stat($file);
1.828     www      9589: 	my $rtncode;
                   9590: 	my $info;
1.538     albertel 9591: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9592: 	if ($lwpresp ne 'ok') {
1.828     www      9593: # there is no such file anymore, even though we had a local copy
1.482     albertel 9594: 	    if ($rtncode eq '404') {
1.538     albertel 9595: 		unlink($file);
1.482     albertel 9596: 	    }
                   9597: 	    return -1;
                   9598: 	}
                   9599: 	if ($info < $fileinfo[9]) {
1.828     www      9600: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9601: 	    return 'ok';
1.828     www      9602: 	} else {
                   9603: # the file is outdated, get rid of it
                   9604: 	    unlink($file);
1.482     albertel 9605: 	}
1.828     www      9606:     }
                   9607: # one way or the other, at this point, we don't have the file
                   9608: # construct the correct path for the file
                   9609:     my @parts = ($cdom,$cnum); 
                   9610:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9611: 	push @parts, split(/\//,$1);
                   9612:     }
                   9613:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9614:     foreach my $part (@parts) {
                   9615: 	$path .= '/'.$part;
                   9616: 	if (!-e $path) {
                   9617: 	    mkdir($path,0770);
1.482     albertel 9618: 	}
                   9619:     }
1.828     www      9620: # now the path exists for sure
                   9621: # get a user agent
                   9622:     my $ua=new LWP::UserAgent;
                   9623:     my $transferfile=$file.'.in.transfer';
                   9624: # FIXME: this should flock
                   9625:     if (-e $transferfile) { return 'ok'; }
                   9626:     my $request;
                   9627:     $uri=~s/^\///;
1.980     raeburn  9628:     my $homeserver = &homeserver($cnum,$cdom);
                   9629:     my $protocol = $protocol{$homeserver};
                   9630:     $protocol = 'http' if ($protocol ne 'https');
                   9631:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9632:     my $response=$ua->request($request,$transferfile);
                   9633: # did it work?
                   9634:     if ($response->is_error()) {
                   9635: 	unlink($transferfile);
                   9636: 	&logthis("Userfile repcopy failed for $uri");
                   9637: 	return -1;
                   9638:     }
                   9639: # worked, rename the transfer file
                   9640:     rename($transferfile,$file);
1.607     raeburn  9641:     return 'ok';
1.481     raeburn  9642: }
                   9643: 
1.517     albertel 9644: sub tokenwrapper {
                   9645:     my $uri=shift;
1.980     raeburn  9646:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9647:     $uri=~s|^/||;
1.620     albertel 9648:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9649:     my $token=$1;
1.552     albertel 9650:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9651:     if ($udom && $uname && $file) {
                   9652: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9653:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9654:         my $homeserver = &homeserver($uname,$udom);
                   9655:         my $protocol = $protocol{$homeserver};
                   9656:         $protocol = 'http' if ($protocol ne 'https');
                   9657:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9658:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9659:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9660:     } else {
                   9661:         return '/adm/notfound.html';
                   9662:     }
                   9663: }
                   9664: 
1.828     www      9665: # call with reqtype HEAD: get last modification time
                   9666: # call with reqtype GET: get the file contents
                   9667: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9668: #
1.481     raeburn  9669: sub getuploaded {
                   9670:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9671:     $uri=~s/^\///;
1.980     raeburn  9672:     my $homeserver = &homeserver($cnum,$cdom);
                   9673:     my $protocol = $protocol{$homeserver};
                   9674:     $protocol = 'http' if ($protocol ne 'https');
                   9675:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9676:     my $ua=new LWP::UserAgent;
                   9677:     my $request=new HTTP::Request($reqtype,$uri);
                   9678:     my $response=$ua->request($request);
                   9679:     $$rtncode = $response->code;
1.482     albertel 9680:     if (! $response->is_success()) {
                   9681: 	return 'failed';
                   9682:     }      
                   9683:     if ($reqtype eq 'HEAD') {
1.486     www      9684: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9685:     } elsif ($reqtype eq 'GET') {
                   9686: 	$$info = $response->content;
1.472     albertel 9687:     }
1.482     albertel 9688:     return 'ok';
1.36      albertel 9689: }
                   9690: 
1.481     raeburn  9691: sub readfile {
                   9692:     my $file = shift;
                   9693:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9694:     my $fh;
                   9695:     open($fh,"<$file");
                   9696:     my $a='';
1.800     albertel 9697:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9698:     return $a;
                   9699: }
                   9700: 
1.36      albertel 9701: sub filelocation {
1.590     banghart 9702:     my ($dir,$file) = @_;
                   9703:     my $location;
                   9704:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9705: 
                   9706:     if ($file =~ m-^/adm/-) {
                   9707: 	$file=~s-^/adm/wrapper/-/-;
                   9708: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9709:     }
1.882     albertel 9710: 
1.590     banghart 9711:     if ($file=~m:^/~:) { # is a contruction space reference
                   9712:         $location = $file;
                   9713:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9714:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9715: 	# is a correct contruction space reference
                   9716:         $location = $file;
1.956     raeburn  9717:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9718:         $location = $file;
1.609     banghart 9719:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9720:         my ($udom,$uname,$filename)=
1.811     albertel 9721:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9722:         my $home=&homeserver($uname,$udom);
                   9723:         my $is_me=0;
                   9724:         my @ids=&current_machine_ids();
                   9725:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9726:         if ($is_me) {
1.955     raeburn  9727:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9728:         } else {
                   9729:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9730:   	      $udom.'/'.$uname.'/'.$filename;
                   9731:         }
1.882     albertel 9732:     } elsif ($file =~ m-^/adm/-) {
                   9733: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9734:     } else {
                   9735:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9736:         $file=~s:^/res/:/:;
                   9737:         if ( !( $file =~ m:^/:) ) {
                   9738:             $location = $dir. '/'.$file;
                   9739:         } else {
                   9740:             $location = '/home/httpd/html/res'.$file;
                   9741:         }
1.59      albertel 9742:     }
1.590     banghart 9743:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9744:     while ($location=~m{/\.\./}) {
                   9745: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9746: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9747: 	} else {
                   9748: 	    $location=~ s{/\.\./}{/}g;
                   9749: 	}
                   9750:     } #remove dir/..
1.590     banghart 9751:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9752:     return $location;
1.46      www      9753: }
1.36      albertel 9754: 
1.46      www      9755: sub hreflocation {
                   9756:     my ($dir,$file)=@_;
1.980     raeburn  9757:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9758: 	$file=filelocation($dir,$file);
1.700     albertel 9759:     } elsif ($file=~m-^/adm/-) {
                   9760: 	$file=~s-^/adm/wrapper/-/-;
                   9761: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9762:     }
                   9763:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9764: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9765:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9766: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9767:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9768: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9769: 	    -/uploaded/$1/$2/-x;
1.46      www      9770:     }
1.913     albertel 9771:     if ($file=~ m{^/userfiles/}) {
                   9772: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9773:     }
1.462     albertel 9774:     return $file;
1.465     albertel 9775: }
                   9776: 
                   9777: sub current_machine_domains {
1.853     albertel 9778:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9779: }
                   9780: 
                   9781: sub machine_domains {
                   9782:     my ($hostname) = @_;
1.465     albertel 9783:     my @domains;
1.838     albertel 9784:     my %hostname = &all_hostnames();
1.465     albertel 9785:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9786: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9787: 	if ($hostname eq $name) {
1.844     albertel 9788: 	    push(@domains,&host_domain($id));
1.465     albertel 9789: 	}
                   9790:     }
                   9791:     return @domains;
                   9792: }
                   9793: 
                   9794: sub current_machine_ids {
1.853     albertel 9795:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9796: }
                   9797: 
                   9798: sub machine_ids {
                   9799:     my ($hostname) = @_;
                   9800:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9801:     my @ids;
1.888     albertel 9802:     my %name_to_host = &all_names();
1.889     albertel 9803:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9804: 	return @{ $name_to_host{$hostname} };
                   9805:     }
                   9806:     return;
1.31      www      9807: }
                   9808: 
1.824     raeburn  9809: sub additional_machine_domains {
                   9810:     my @domains;
                   9811:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9812:     while( my $line = <$fh>) {
                   9813:         $line =~ s/\s//g;
                   9814:         push(@domains,$line);
                   9815:     }
                   9816:     return @domains;
                   9817: }
                   9818: 
                   9819: sub default_login_domain {
                   9820:     my $domain = $perlvar{'lonDefDomain'};
                   9821:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9822:     foreach my $posdom (&current_machine_domains(),
                   9823:                         &additional_machine_domains()) {
                   9824:         if (lc($posdom) eq lc($testdomain)) {
                   9825:             $domain=$posdom;
                   9826:             last;
                   9827:         }
                   9828:     }
                   9829:     return $domain;
                   9830: }
                   9831: 
1.31      www      9832: # ------------------------------------------------------------- Declutters URLs
                   9833: 
                   9834: sub declutter {
                   9835:     my $thisfn=shift;
1.569     albertel 9836:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9837:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9838:     $thisfn=~s/^\///;
1.697     albertel 9839:     $thisfn=~s|^adm/wrapper/||;
                   9840:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9841:     $thisfn=~s/^res\///;
1.1032    raeburn  9842:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9843:         $thisfn=~s/\?.+$//;
                   9844:     }
1.268     www      9845:     return $thisfn;
                   9846: }
                   9847: 
                   9848: # ------------------------------------------------------------- Clutter up URLs
                   9849: 
                   9850: sub clutter {
                   9851:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9852:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9853: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9854:        $thisfn='/res'.$thisfn; 
                   9855:     }
1.1031    raeburn  9856:     if ($thisfn !~m|^/adm|) {
                   9857: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9858: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9859: 	} else {
                   9860: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9861: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9862: 	    if ($embstyle eq 'ssi'
                   9863: 		|| ($embstyle eq 'hdn')
                   9864: 		|| ($embstyle eq 'rat')
                   9865: 		|| ($embstyle eq 'prv')
                   9866: 		|| ($embstyle eq 'ign')) {
                   9867: 		#do nothing with these
                   9868: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9869: 		|| ($embstyle eq 'emb')
                   9870: 		|| ($embstyle eq 'wrp')) {
                   9871: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9872: 	    } elsif ($embstyle eq 'unk'
                   9873: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9874: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9875: 	    } else {
1.718     www      9876: #		&logthis("Got a blank emb style");
1.695     albertel 9877: 	    }
1.694     albertel 9878: 	}
                   9879:     }
1.31      www      9880:     return $thisfn;
1.12      www      9881: }
                   9882: 
1.787     albertel 9883: sub clutter_with_no_wrapper {
                   9884:     my $uri = &clutter(shift);
                   9885:     if ($uri =~ m-^/adm/-) {
                   9886: 	$uri =~ s-^/adm/wrapper/-/-;
                   9887: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9888:     }
                   9889:     return $uri;
                   9890: }
                   9891: 
1.557     albertel 9892: sub freeze_escape {
                   9893:     my ($value)=@_;
                   9894:     if (ref($value)) {
                   9895: 	$value=&nfreeze($value);
                   9896: 	return '__FROZEN__'.&escape($value);
                   9897:     }
                   9898:     return &escape($value);
                   9899: }
                   9900: 
1.11      www      9901: 
1.557     albertel 9902: sub thaw_unescape {
                   9903:     my ($value)=@_;
                   9904:     if ($value =~ /^__FROZEN__/) {
                   9905: 	substr($value,0,10,undef);
                   9906: 	$value=&unescape($value);
                   9907: 	return &thaw($value);
                   9908:     }
                   9909:     return &unescape($value);
                   9910: }
                   9911: 
1.436     albertel 9912: sub correct_line_ends {
                   9913:     my ($result)=@_;
                   9914:     $$result =~s/\r\n/\n/mg;
                   9915:     $$result =~s/\r/\n/mg;
1.415     albertel 9916: }
1.1       albertel 9917: # ================================================================ Main Program
                   9918: 
1.184     www      9919: sub goodbye {
1.204     albertel 9920:    &logthis("Starting Shut down");
1.443     albertel 9921: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9922:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9923: #converted
1.599     albertel 9924: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9925:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9926: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9927: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9928: #1.1 only
1.870     albertel 9929: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9930: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9931: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9932: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9933:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9934:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9935:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9936:    &flushcourselogs();
                   9937:    &logthis("Shutting down");
                   9938: }
                   9939: 
1.852     albertel 9940: sub get_dns {
1.869     albertel 9941:     my ($url,$func,$ignore_cache) = @_;
                   9942:     if (!$ignore_cache) {
                   9943: 	my ($content,$cached)=
                   9944: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9945: 	if ($cached) {
                   9946: 	    &$func($content);
                   9947: 	    return;
                   9948: 	}
                   9949:     }
                   9950: 
                   9951:     my %alldns;
1.852     albertel 9952:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9953:     foreach my $dns (<$config>) {
                   9954: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9955:         my $line = $1;
                   9956:         my ($host,$protocol) = split(/:/,$line);
                   9957:         if ($protocol ne 'https') {
                   9958:             $protocol = 'http';
                   9959:         }
                   9960: 	$alldns{$host} = $protocol;
1.869     albertel 9961:     }
                   9962:     while (%alldns) {
                   9963: 	my ($dns) = keys(%alldns);
1.852     albertel 9964: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9965: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9966: 	my $response=$ua->request($request);
1.979     raeburn  9967:         delete($alldns{$dns});
1.852     albertel 9968: 	next if ($response->is_error());
                   9969: 	my @content = split("\n",$response->content);
1.869     albertel 9970: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9971: 	&$func(\@content);
1.869     albertel 9972: 	return;
1.852     albertel 9973:     }
                   9974:     close($config);
1.871     albertel 9975:     my $which = (split('/',$url))[3];
                   9976:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9977:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9978:     my @content = <$config>;
                   9979:     &$func(\@content);
                   9980:     return;
1.852     albertel 9981: }
1.327     albertel 9982: # ------------------------------------------------------------ Read domain file
                   9983: {
1.852     albertel 9984:     my $loaded;
1.846     albertel 9985:     my %domain;
                   9986: 
1.852     albertel 9987:     sub parse_domain_tab {
                   9988: 	my ($lines) = @_;
                   9989: 	foreach my $line (@$lines) {
                   9990: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9991: 
1.846     albertel 9992: 	    chomp($line);
1.852     albertel 9993: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9994: 	    my %this_domain;
                   9995: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9996: 			       'lang_def', 'city', 'longi', 'lati',
                   9997: 			       'primary') {
                   9998: 		$this_domain{$field} = shift(@elements);
                   9999: 	    }
                   10000: 	    $domain{$name} = \%this_domain;
1.852     albertel 10001: 	}
                   10002:     }
1.864     albertel 10003: 
                   10004:     sub reset_domain_info {
                   10005: 	undef($loaded);
                   10006: 	undef(%domain);
                   10007:     }
                   10008: 
1.852     albertel 10009:     sub load_domain_tab {
1.869     albertel 10010: 	my ($ignore_cache) = @_;
                   10011: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10012: 	my $fh;
                   10013: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10014: 	    my @lines = <$fh>;
                   10015: 	    &parse_domain_tab(\@lines);
1.448     albertel 10016: 	}
1.852     albertel 10017: 	close($fh);
                   10018: 	$loaded = 1;
1.327     albertel 10019:     }
1.846     albertel 10020: 
                   10021:     sub domain {
1.852     albertel 10022: 	&load_domain_tab() if (!$loaded);
                   10023: 
1.846     albertel 10024: 	my ($name,$what) = @_;
                   10025: 	return if ( !exists($domain{$name}) );
                   10026: 
                   10027: 	if (!$what) {
                   10028: 	    return $domain{$name}{'description'};
                   10029: 	}
                   10030: 	return $domain{$name}{$what};
                   10031:     }
1.974     raeburn  10032: 
                   10033:     sub domain_info {
                   10034:         &load_domain_tab() if (!$loaded);
                   10035:         return %domain;
                   10036:     }
                   10037: 
1.327     albertel 10038: }
                   10039: 
                   10040: 
1.1       albertel 10041: # ------------------------------------------------------------- Read hosts file
                   10042: {
1.838     albertel 10043:     my %hostname;
1.844     albertel 10044:     my %hostdom;
1.845     albertel 10045:     my %libserv;
1.852     albertel 10046:     my $loaded;
1.888     albertel 10047:     my %name_to_host;
1.1056.4.6  raeburn  10048:     my %internetdom;
1.852     albertel 10049: 
                   10050:     sub parse_hosts_tab {
                   10051: 	my ($file) = @_;
                   10052: 	foreach my $configline (@$file) {
                   10053: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10054: 	    next if ($configline =~ /^\^/);
                   10055: 	    chomp($configline);
1.1056.4.6  raeburn  10056: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10057: 	    $name=~s/\s//g;
                   10058: 	    if ($id && $domain && $role && $name) {
                   10059: 		$hostname{$id}=$name;
1.888     albertel 10060: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10061: 		$hostdom{$id}=$domain;
                   10062: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10063:                 if (defined($protocol)) {
                   10064:                     if ($protocol eq 'https') {
                   10065:                         $protocol{$id} = $protocol;
                   10066:                     } else {
                   10067:                         $protocol{$id} = 'http'; 
                   10068:                     }
1.968     raeburn  10069:                 } else {
1.969     raeburn  10070:                     $protocol{$id} = 'http';
1.968     raeburn  10071:                 }
1.1056.4.6  raeburn  10072:                 if (defined($intdom)) {
                   10073:                     $internetdom{$id} = $intdom;
                   10074:                 }
1.852     albertel 10075: 	    }
                   10076: 	}
                   10077:     }
1.864     albertel 10078:     
                   10079:     sub reset_hosts_info {
1.897     albertel 10080: 	&purge_remembered();
1.864     albertel 10081: 	&reset_domain_info();
                   10082: 	&reset_hosts_ip_info();
1.892     albertel 10083: 	undef(%name_to_host);
1.864     albertel 10084: 	undef(%hostname);
                   10085: 	undef(%hostdom);
                   10086: 	undef(%libserv);
                   10087: 	undef($loaded);
                   10088:     }
1.1       albertel 10089: 
1.852     albertel 10090:     sub load_hosts_tab {
1.869     albertel 10091: 	my ($ignore_cache) = @_;
                   10092: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10093: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10094: 	my @config = <$config>;
                   10095: 	&parse_hosts_tab(\@config);
                   10096: 	close($config);
                   10097: 	$loaded=1;
1.1       albertel 10098:     }
1.852     albertel 10099: 
1.838     albertel 10100:     sub hostname {
1.852     albertel 10101: 	&load_hosts_tab() if (!$loaded);
                   10102: 
1.838     albertel 10103: 	my ($lonid) = @_;
                   10104: 	return $hostname{$lonid};
                   10105:     }
1.845     albertel 10106: 
1.838     albertel 10107:     sub all_hostnames {
1.852     albertel 10108: 	&load_hosts_tab() if (!$loaded);
                   10109: 
1.838     albertel 10110: 	return %hostname;
                   10111:     }
1.845     albertel 10112: 
1.888     albertel 10113:     sub all_names {
                   10114: 	&load_hosts_tab() if (!$loaded);
                   10115: 
                   10116: 	return %name_to_host;
                   10117:     }
                   10118: 
1.974     raeburn  10119:     sub all_host_domain {
                   10120:         &load_hosts_tab() if (!$loaded);
                   10121:         return %hostdom;
                   10122:     }
                   10123: 
1.845     albertel 10124:     sub is_library {
1.852     albertel 10125: 	&load_hosts_tab() if (!$loaded);
                   10126: 
1.845     albertel 10127: 	return exists($libserv{$_[0]});
                   10128:     }
                   10129: 
                   10130:     sub all_library {
1.852     albertel 10131: 	&load_hosts_tab() if (!$loaded);
                   10132: 
1.845     albertel 10133: 	return %libserv;
                   10134:     }
                   10135: 
1.1056.4.2  raeburn  10136:     sub unique_library {
                   10137:         #2x reverse removes all hostnames that appear more than once
                   10138:         my %unique = reverse &all_library();
                   10139:         return reverse %unique;
                   10140:     }
                   10141: 
1.841     albertel 10142:     sub get_servers {
1.852     albertel 10143: 	&load_hosts_tab() if (!$loaded);
                   10144: 
1.841     albertel 10145: 	my ($domain,$type) = @_;
                   10146: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10147: 	                                          : %hostname;
                   10148: 	my %result;
1.842     albertel 10149: 	if (ref($domain) eq 'ARRAY') {
                   10150: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10151: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10152: 		    $result{$host} = $hostname;
                   10153: 		}
                   10154: 	    }
                   10155: 	} else {
                   10156: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10157: 		if ($hostdom{$host} eq $domain) {
                   10158: 		    $result{$host} = $hostname;
                   10159: 		}
1.841     albertel 10160: 	    }
                   10161: 	}
                   10162: 	return %result;
                   10163:     }
1.845     albertel 10164: 
1.1056.4.2  raeburn  10165:     sub get_unique_servers {
                   10166:         my %unique = reverse &get_servers(@_);
                   10167:         return reverse %unique;
                   10168:     }
                   10169: 
1.844     albertel 10170:     sub host_domain {
1.852     albertel 10171: 	&load_hosts_tab() if (!$loaded);
                   10172: 
1.844     albertel 10173: 	my ($lonid) = @_;
                   10174: 	return $hostdom{$lonid};
                   10175:     }
                   10176: 
1.841     albertel 10177:     sub all_domains {
1.852     albertel 10178: 	&load_hosts_tab() if (!$loaded);
                   10179: 
1.841     albertel 10180: 	my %seen;
                   10181: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10182: 	return @uniq;
                   10183:     }
1.1056.4.3  raeburn  10184: 
                   10185:     sub internet_dom {
                   10186:         &load_hosts_tab() if (!$loaded);
                   10187: 
                   10188:         my ($lonid) = @_;
                   10189:         return $internetdom{$lonid};
                   10190:     }
1.1       albertel 10191: }
                   10192: 
1.847     albertel 10193: { 
                   10194:     my %iphost;
1.856     albertel 10195:     my %name_to_ip;
                   10196:     my %lonid_to_ip;
1.869     albertel 10197: 
1.847     albertel 10198:     sub get_hosts_from_ip {
                   10199: 	my ($ip) = @_;
                   10200: 	my %iphosts = &get_iphost();
                   10201: 	if (ref($iphosts{$ip})) {
                   10202: 	    return @{$iphosts{$ip}};
                   10203: 	}
                   10204: 	return;
1.839     albertel 10205:     }
1.864     albertel 10206:     
                   10207:     sub reset_hosts_ip_info {
                   10208: 	undef(%iphost);
                   10209: 	undef(%name_to_ip);
                   10210: 	undef(%lonid_to_ip);
                   10211:     }
1.856     albertel 10212: 
                   10213:     sub get_host_ip {
                   10214: 	my ($lonid) = @_;
                   10215: 	if (exists($lonid_to_ip{$lonid})) {
                   10216: 	    return $lonid_to_ip{$lonid};
                   10217: 	}
                   10218: 	my $name=&hostname($lonid);
                   10219:    	my $ip = gethostbyname($name);
                   10220: 	return if (!$ip || length($ip) ne 4);
                   10221: 	$ip=inet_ntoa($ip);
                   10222: 	$name_to_ip{$name}   = $ip;
                   10223: 	$lonid_to_ip{$lonid} = $ip;
                   10224: 	return $ip;
                   10225:     }
1.847     albertel 10226:     
                   10227:     sub get_iphost {
1.869     albertel 10228: 	my ($ignore_cache) = @_;
1.894     albertel 10229: 
1.869     albertel 10230: 	if (!$ignore_cache) {
                   10231: 	    if (%iphost) {
                   10232: 		return %iphost;
                   10233: 	    }
                   10234: 	    my ($ip_info,$cached)=
                   10235: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10236: 	    if ($cached) {
                   10237: 		%iphost      = %{$ip_info->[0]};
                   10238: 		%name_to_ip  = %{$ip_info->[1]};
                   10239: 		%lonid_to_ip = %{$ip_info->[2]};
                   10240: 		return %iphost;
                   10241: 	    }
                   10242: 	}
1.894     albertel 10243: 
                   10244: 	# get yesterday's info for fallback
                   10245: 	my %old_name_to_ip;
                   10246: 	my ($ip_info,$cached)=
                   10247: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10248: 	if ($cached) {
                   10249: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10250: 	}
                   10251: 
1.888     albertel 10252: 	my %name_to_host = &all_names();
                   10253: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10254: 	    my $ip;
                   10255: 	    if (!exists($name_to_ip{$name})) {
                   10256: 		$ip = gethostbyname($name);
                   10257: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10258: 		    if (defined($old_name_to_ip{$name})) {
                   10259: 			$ip = $old_name_to_ip{$name};
                   10260: 			&logthis("Can't find $name defaulting to old $ip");
                   10261: 		    } else {
                   10262: 			&logthis("Name $name no IP found");
                   10263: 			next;
                   10264: 		    }
                   10265: 		} else {
                   10266: 		    $ip=inet_ntoa($ip);
1.847     albertel 10267: 		}
                   10268: 		$name_to_ip{$name} = $ip;
                   10269: 	    } else {
                   10270: 		$ip = $name_to_ip{$name};
1.653     albertel 10271: 	    }
1.888     albertel 10272: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10273: 		$lonid_to_ip{$id} = $ip;
                   10274: 	    }
                   10275: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10276: 	}
1.869     albertel 10277: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10278: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10279: 				      48*60*60);
1.869     albertel 10280: 
1.847     albertel 10281: 	return %iphost;
1.598     albertel 10282:     }
                   10283: 
1.992     raeburn  10284:     #
                   10285:     #  Given a DNS returns the loncapa host name for that DNS 
                   10286:     # 
                   10287:     sub host_from_dns {
                   10288:         my ($dns) = @_;
                   10289:         my @hosts;
                   10290:         my $ip;
                   10291: 
1.993     raeburn  10292:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10293:             $ip = $name_to_ip{$dns};
                   10294:         }
                   10295:         if (!$ip) {
                   10296:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10297:             if (length($ip) == 4) { 
                   10298: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10299:             }
                   10300:         }
                   10301:         if ($ip) {
                   10302: 	    @hosts = get_hosts_from_ip($ip);
                   10303: 	    return $hosts[0];
                   10304:         }
                   10305:         return undef;
1.986     foxr     10306:     }
1.992     raeburn  10307: 
1.1056.4.3  raeburn  10308:     sub get_internet_names {
                   10309:         my ($lonid) = @_;
                   10310:         return if ($lonid eq '');
                   10311:         my ($idnref,$cached)=
                   10312:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10313:         if ($cached) {
                   10314:             return $idnref;
                   10315:         }
                   10316:         my $ip = &get_host_ip($lonid);
                   10317:         my @hosts = &get_hosts_from_ip($ip);
                   10318:         my %iphost = &get_iphost();
                   10319:         my (@idns,%seen);
                   10320:         foreach my $id (@hosts) {
                   10321:             my $dom = &host_domain($id);
                   10322:             my $prim_id = &domain($dom,'primary');
                   10323:             my $prim_ip = &get_host_ip($prim_id);
                   10324:             next if ($seen{$prim_ip});
                   10325:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10326:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10327:                     my $intdom = &internet_dom($id);
                   10328:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10329:                         push(@idns,$intdom);
                   10330:                     }
                   10331:                 }
                   10332:             }
                   10333:             $seen{$prim_ip} = 1;
                   10334:         }
                   10335:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10336:     }
                   10337: 
                   10338: }
                   10339: 
                   10340: sub all_loncaparevs {
                   10341:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986     foxr     10342: }
                   10343: 
1.862     albertel 10344: BEGIN {
                   10345: 
                   10346: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10347:     unless ($readit) {
                   10348: {
                   10349:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10350:     %perlvar = (%perlvar,%{$configvars});
                   10351: }
                   10352: 
                   10353: 
1.1       albertel 10354: # ------------------------------------------------------ Read spare server file
                   10355: {
1.448     albertel 10356:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10357: 
                   10358:     while (my $configline=<$config>) {
                   10359:        chomp($configline);
1.284     matthew  10360:        if ($configline) {
1.784     albertel 10361: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10362: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10363: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10364:        }
                   10365:     }
1.448     albertel 10366:     close($config);
1.1       albertel 10367: }
1.11      www      10368: # ------------------------------------------------------------ Read permissions
                   10369: {
1.448     albertel 10370:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10371: 
                   10372:     while (my $configline=<$config>) {
1.448     albertel 10373: 	chomp($configline);
                   10374: 	if ($configline) {
                   10375: 	    my ($role,$perm)=split(/ /,$configline);
                   10376: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10377: 	}
1.11      www      10378:     }
1.448     albertel 10379:     close($config);
1.11      www      10380: }
                   10381: 
                   10382: # -------------------------------------------- Read plain texts for permissions
                   10383: {
1.448     albertel 10384:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10385: 
                   10386:     while (my $configline=<$config>) {
1.448     albertel 10387: 	chomp($configline);
                   10388: 	if ($configline) {
1.742     raeburn  10389: 	    my ($short,@plain)=split(/:/,$configline);
                   10390:             %{$prp{$short}} = ();
                   10391: 	    if (@plain > 0) {
                   10392:                 $prp{$short}{'std'} = $plain[0];
                   10393:                 for (my $i=1; $i<@plain; $i++) {
                   10394:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10395:                 }
                   10396:             }
1.448     albertel 10397: 	}
1.135     www      10398:     }
1.448     albertel 10399:     close($config);
1.135     www      10400: }
                   10401: 
                   10402: # ---------------------------------------------------------- Read package table
                   10403: {
1.448     albertel 10404:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10405: 
                   10406:     while (my $configline=<$config>) {
1.483     albertel 10407: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10408: 	chomp($configline);
                   10409: 	my ($short,$plain)=split(/:/,$configline);
                   10410: 	my ($pack,$name)=split(/\&/,$short);
                   10411: 	if ($plain ne '') {
                   10412: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10413: 	    $packagetab{$short}=$plain; 
                   10414: 	}
1.11      www      10415:     }
1.448     albertel 10416:     close($config);
1.329     matthew  10417: }
                   10418: 
1.1056.4.3  raeburn  10419: # ---------------------------------------------------------- Read loncaparev table
                   10420: {
                   10421:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10422:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10423:             while (my $configline=<$config>) {
                   10424:                 chomp($configline);
                   10425:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10426:                 $loncaparevs{$hostid}=$loncaparev;
                   10427:             }
                   10428:             close($config);
                   10429:         }
                   10430:     }
                   10431: }
                   10432: 
                   10433: # ---------------------------------------------------------- Read serverhostID table
                   10434: {
                   10435:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10436:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10437:             while (my $configline=<$config>) {
                   10438:                 chomp($configline);
                   10439:                 my ($name,$id)=split(/:/,$configline);
                   10440:                 $serverhomeIDs{$name}=$id;
                   10441:             }
                   10442:             close($config);
                   10443:         }
                   10444:     }
                   10445: }
                   10446: 
1.1056.4.5  raeburn  10447: {
                   10448:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10449:     if (-e $file) {
                   10450:         my $parser = HTML::LCParser->new($file);
                   10451:         while (my $token = $parser->get_token()) {
                   10452:             if ($token->[0] eq 'S') {
                   10453:                 my $item = $token->[1];
                   10454:                 my $name = $token->[2]{'name'};
                   10455:                 my $value = $token->[2]{'value'};
                   10456:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10457:                     my $release = $parser->get_text();
                   10458:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10459:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10460:                 }
                   10461:             }
                   10462:         }
                   10463:     }
                   10464: }
                   10465: 
1.329     matthew  10466: # ------------- set up temporary directory
                   10467: {
                   10468:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10469: 
1.11      www      10470: }
                   10471: 
1.794     albertel 10472: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10473: 				'compress_threshold'=> 20_000,
                   10474:  			        });
1.185     www      10475: 
1.281     www      10476: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10477: $dumpcount=0;
1.958     www      10478: $locknum=0;
1.22      www      10479: 
1.163     harris41 10480: &logtouch();
1.672     albertel 10481: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10482: $readit=1;
1.564     albertel 10483:     {
                   10484: 	use integer;
                   10485: 	my $test=(2**32)+1;
1.568     albertel 10486: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10487: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10488:     }
1.195     www      10489: }
1.1       albertel 10490: }
1.179     www      10491: 
1.1       albertel 10492: 1;
1.191     harris41 10493: __END__
                   10494: 
1.243     albertel 10495: =pod
                   10496: 
1.191     harris41 10497: =head1 NAME
                   10498: 
1.243     albertel 10499: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10500: 
                   10501: =head1 SYNOPSIS
                   10502: 
1.243     albertel 10503: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10504: 
                   10505:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10506: 
1.243     albertel 10507: Common parameters:
                   10508: 
                   10509: =over 4
                   10510: 
                   10511: =item *
                   10512: 
                   10513: $uname : an internal username (if $cname expecting a course Id specifically)
                   10514: 
                   10515: =item *
                   10516: 
                   10517: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10518: 
                   10519: =item *
                   10520: 
                   10521: $symb : a resource instance identifier
                   10522: 
                   10523: =item *
                   10524: 
                   10525: $namespace : the name of a .db file that contains the data needed or
                   10526: being set.
                   10527: 
                   10528: =back
                   10529: 
1.394     bowersj2 10530: =head1 OVERVIEW
1.191     harris41 10531: 
1.394     bowersj2 10532: lonnet provides subroutines which interact with the
                   10533: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10534: about classes, users, and resources.
1.243     albertel 10535: 
                   10536: For many of these objects you can also use this to store data about
                   10537: them or modify them in various ways.
1.191     harris41 10538: 
1.394     bowersj2 10539: =head2 Symbs
1.191     harris41 10540: 
1.394     bowersj2 10541: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10542: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10543: map, the resource number of the resource in the map, and the URL of
                   10544: the resource itself. The latter is somewhat redundant, but might help
                   10545: if maps change.
                   10546: 
                   10547: An example is
                   10548: 
                   10549:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10550: 
                   10551: The respective map entry is
                   10552: 
                   10553:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10554:   title="Problem 2">
                   10555:  </resource>
                   10556: 
                   10557: Symbs are used by the random number generator, as well as to store and
                   10558: restore data specific to a certain instance of for example a problem.
                   10559: 
                   10560: =head2 Storing And Retrieving Data
                   10561: 
                   10562: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10563: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10564: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10565: is is the non-critical message twin of cstore. These functions are for
                   10566: handlers to store a perl hash to a user's permanent data space in an
                   10567: easy manner, and to retrieve it again on another call. It is expected
                   10568: that a handler would use this once at the beginning to retrieve data,
                   10569: and then again once at the end to send only the new data back.
                   10570: 
                   10571: The data is stored in the user's data directory on the user's
                   10572: homeserver under the ID of the course.
                   10573: 
                   10574: The hash that is returned by restore will have all of the previous
                   10575: value for all of the elements of the hash.
                   10576: 
                   10577: Example:
                   10578: 
                   10579:  #creating a hash
                   10580:  my %hash;
                   10581:  $hash{'foo'}='bar';
                   10582: 
                   10583:  #storing it
                   10584:  &Apache::lonnet::cstore(\%hash);
                   10585: 
                   10586:  #changing a value
                   10587:  $hash{'foo'}='notbar';
                   10588: 
                   10589:  #adding a new value
                   10590:  $hash{'bar'}='foo';
                   10591:  &Apache::lonnet::cstore(\%hash);
                   10592: 
                   10593:  #retrieving the hash
                   10594:  my %history=&Apache::lonnet::restore();
                   10595: 
                   10596:  #print the hash
                   10597:  foreach my $key (sort(keys(%history))) {
                   10598:    print("\%history{$key} = $history{$key}");
                   10599:  }
                   10600: 
                   10601: Will print out:
1.191     harris41 10602: 
1.394     bowersj2 10603:  %history{1:foo} = bar
                   10604:  %history{1:keys} = foo:timestamp
                   10605:  %history{1:timestamp} = 990455579
                   10606:  %history{2:bar} = foo
                   10607:  %history{2:foo} = notbar
                   10608:  %history{2:keys} = foo:bar:timestamp
                   10609:  %history{2:timestamp} = 990455580
                   10610:  %history{bar} = foo
                   10611:  %history{foo} = notbar
                   10612:  %history{timestamp} = 990455580
                   10613:  %history{version} = 2
                   10614: 
                   10615: Note that the special hash entries C<keys>, C<version> and
                   10616: C<timestamp> were added to the hash. C<version> will be equal to the
                   10617: total number of versions of the data that have been stored. The
                   10618: C<timestamp> attribute will be the UNIX time the hash was
                   10619: stored. C<keys> is available in every historical section to list which
                   10620: keys were added or changed at a specific historical revision of a
                   10621: hash.
                   10622: 
                   10623: B<Warning>: do not store the hash that restore returns directly. This
                   10624: will cause a mess since it will restore the historical keys as if the
                   10625: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10626: 
1.394     bowersj2 10627: Calling convention:
1.191     harris41 10628: 
1.394     bowersj2 10629:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10630:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10631: 
1.394     bowersj2 10632: For more detailed information, see lonnet specific documentation.
1.191     harris41 10633: 
1.394     bowersj2 10634: =head1 RETURN MESSAGES
1.191     harris41 10635: 
1.394     bowersj2 10636: =over 4
1.191     harris41 10637: 
1.394     bowersj2 10638: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10639: 
1.394     bowersj2 10640: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10641: when the connection is brought back up
1.191     harris41 10642: 
1.394     bowersj2 10643: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10644: for later delivery
1.191     harris41 10645: 
1.967     bisitz   10646: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10647: 
1.394     bowersj2 10648: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10649: that was requested
1.191     harris41 10650: 
1.243     albertel 10651: =back
1.191     harris41 10652: 
1.243     albertel 10653: =head1 PUBLIC SUBROUTINES
1.191     harris41 10654: 
1.243     albertel 10655: =head2 Session Environment Functions
1.191     harris41 10656: 
1.243     albertel 10657: =over 4
1.191     harris41 10658: 
1.394     bowersj2 10659: =item * 
                   10660: X<appenv()>
1.949     raeburn  10661: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10662: the user envirnoment file, and will be restored for each access this
1.620     albertel 10663: user makes during this session, also modifies the %env for the current
1.949     raeburn  10664: process. Optional rolesarrayref - if defined contains a reference to an array
                   10665: of roles which are exempt from the restriction on modifying user.role entries 
                   10666: in the user's environment.db and in %env.    
1.191     harris41 10667: 
                   10668: =item *
1.394     bowersj2 10669: X<delenv()>
1.987     raeburn  10670: B<delenv($delthis,$regexp)>: removes all items from the session
                   10671: environment file that begin with $delthis. If the 
                   10672: optional second arg - $regexp - is true, $delthis is treated as a 
                   10673: regular expression, otherwise \Q$delthis\E is used. 
                   10674: The values are also deleted from the current processes %env.
1.191     harris41 10675: 
1.795     albertel 10676: =item * get_env_multiple($name) 
                   10677: 
                   10678: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10679: values may be defined and end up as an array ref.
                   10680: 
                   10681: returns an array of values
                   10682: 
1.243     albertel 10683: =back
                   10684: 
                   10685: =head2 User Information
1.191     harris41 10686: 
1.243     albertel 10687: =over 4
1.191     harris41 10688: 
                   10689: =item *
1.394     bowersj2 10690: X<queryauthenticate()>
                   10691: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10692: authentication scheme
                   10693: 
                   10694: =item *
1.394     bowersj2 10695: X<authenticate()>
1.1056.4.3  raeburn  10696: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10697: authenticate user from domain's lib servers (first use the current
                   10698: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10699: $checkdefauth is optional (value is 1 if a check should be made to
                   10700:    authenticate user using default authentication method, and allow
                   10701:    account creation if username does not have account in the domain).
                   10702: $clientcancheckhost is optional (value is 1 if checking whether the
                   10703:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10704: 
                   10705: =item *
1.394     bowersj2 10706: X<homeserver()>
                   10707: B<homeserver($uname,$udom)>: find the server which has
                   10708: the user's directory and files (there must be only one), this caches
                   10709: the answer, and also caches if there is a borken connection.
1.191     harris41 10710: 
                   10711: =item *
1.394     bowersj2 10712: X<idget()>
                   10713: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10714: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10715: username, and only 1 username per ID in a specific domain) (returns
                   10716: hash: id=>name,id=>name)
1.191     harris41 10717: 
                   10718: =item *
1.394     bowersj2 10719: X<idrget()>
                   10720: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10721: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10722: 
                   10723: =item *
1.394     bowersj2 10724: X<idput()>
                   10725: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10726: 
                   10727: =item *
1.394     bowersj2 10728: X<rolesinit()>
                   10729: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10730: 
                   10731: =item *
1.551     albertel 10732: X<getsection()>
                   10733: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10734: course $cname, return section name/number or '' for "not in course"
                   10735: and '-1' for "no section"
                   10736: 
                   10737: =item *
1.394     bowersj2 10738: X<userenvironment()>
                   10739: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10740: passed in @what from the requested user's environment, returns a hash
                   10741: 
1.858     raeburn  10742: =item * 
                   10743: X<userlog_query()>
1.859     albertel 10744: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10745: activity.log file. %filters defines filters applied when parsing the
                   10746: log file. These can be start or end timestamps, or the type of action
                   10747: - log to look for Login or Logout events, check for Checkin or
                   10748: Checkout, role for role selection. The response is in the form
                   10749: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10750: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10751: 
1.243     albertel 10752: =back
                   10753: 
                   10754: =head2 User Roles
                   10755: 
                   10756: =over 4
                   10757: 
                   10758: =item *
                   10759: 
1.810     raeburn  10760: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10761:  F: full access
                   10762:  U,I,K: authentication modes (cxx only)
                   10763:  '': forbidden
                   10764:  1: user needs to choose course
                   10765:  2: browse allowed
1.766     albertel 10766:  A: passphrase authentication needed
1.243     albertel 10767: 
                   10768: =item *
                   10769: 
                   10770: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10771: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10772: and course level
                   10773: 
                   10774: =item *
                   10775: 
1.988     raeburn  10776: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10777: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10778: $type is Course (default) or Community.
1.988     raeburn  10779: If $forcedefault evaluates to true, text returned will be default 
                   10780: text for $type. Otherwise, if this is a course, the text returned 
                   10781: will be a custom name for the role (if defined in the course's 
                   10782: environment).  If no custom name is defined the default is returned.
                   10783:    
1.832     raeburn  10784: =item *
                   10785: 
1.935     raeburn  10786: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10787: All arguments are optional. Returns a hash of a roles, either for
                   10788: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10789: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10790: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10791: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10792: For each key, value is set to colon-separated start and end times for
                   10793: the role.  If no username and domain are specified, will default to
1.934     raeburn  10794: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10795: of role statuses (active, future or previous), roles 
                   10796: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10797: to restrict the list of roles reported. If no array ref is 
                   10798: provided for types, will default to return only active roles.
1.834     albertel 10799: 
1.243     albertel 10800: =back
                   10801: 
                   10802: =head2 User Modification
                   10803: 
                   10804: =over 4
                   10805: 
                   10806: =item *
                   10807: 
1.957     raeburn  10808: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10809: user for the level given by URL.  Optional start and end dates (leave empty
                   10810: string or zero for "no date")
1.191     harris41 10811: 
                   10812: =item *
                   10813: 
1.243     albertel 10814: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10815: change a users, password, possible return values are: ok,
                   10816: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10817: refused
1.191     harris41 10818: 
                   10819: =item *
                   10820: 
1.243     albertel 10821: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10822: 
                   10823: =item *
                   10824: 
1.1056.4.1  raeburn  10825: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10826:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10827: 
                   10828: will update user information (firstname,middlename,lastname,generation,
                   10829: permanentemail), and if forceid is true, student/employee ID also.
                   10830: A user's institutional affiliation(s) can also be updated.
                   10831: User information fields will not be overwritten with empty entries 
                   10832: unless the field is included in the $candelete array reference.
                   10833: This array is included when a single user is modified via "Manage Users",
                   10834: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10835: 
                   10836: =item *
                   10837: 
1.286     matthew  10838: modifystudent
                   10839: 
1.957     raeburn  10840: modify a student's enrollment and identification information.
1.286     matthew  10841: The course id is resolved based on the current users environment.  
                   10842: This means the envoking user must be a course coordinator or otherwise
                   10843: associated with a course.
                   10844: 
1.297     matthew  10845: This call is essentially a wrapper for lonnet::modifyuser and
                   10846: lonnet::modify_student_enrollment
1.286     matthew  10847: 
                   10848: Inputs: 
                   10849: 
                   10850: =over 4
                   10851: 
1.957     raeburn  10852: =item B<$udom> Student's loncapa domain
1.286     matthew  10853: 
1.957     raeburn  10854: =item B<$uname> Student's loncapa login name
1.286     matthew  10855: 
1.964     bisitz   10856: =item B<$uid> Student/Employee ID
1.286     matthew  10857: 
1.957     raeburn  10858: =item B<$umode> Student's authentication mode
1.286     matthew  10859: 
1.957     raeburn  10860: =item B<$upass> Student's password
1.286     matthew  10861: 
1.957     raeburn  10862: =item B<$first> Student's first name
1.286     matthew  10863: 
1.957     raeburn  10864: =item B<$middle> Student's middle name
1.286     matthew  10865: 
1.957     raeburn  10866: =item B<$last> Student's last name
1.286     matthew  10867: 
1.957     raeburn  10868: =item B<$gene> Student's generation
1.286     matthew  10869: 
1.957     raeburn  10870: =item B<$usec> Student's section in course
1.286     matthew  10871: 
                   10872: =item B<$end> Unix time of the roles expiration
                   10873: 
                   10874: =item B<$start> Unix time of the roles start date
                   10875: 
                   10876: =item B<$forceid> If defined, allow $uid to be changed
                   10877: 
                   10878: =item B<$desiredhome> server to use as home server for student
                   10879: 
1.957     raeburn  10880: =item B<$email> Student's permanent e-mail address
                   10881: 
                   10882: =item B<$type> Type of enrollment (auto or manual)
                   10883: 
1.963     raeburn  10884: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10885: 
                   10886: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10887: 
1.963     raeburn  10888: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10889: 
1.963     raeburn  10890: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10891: 
1.963     raeburn  10892: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10893: 
1.286     matthew  10894: =back
1.297     matthew  10895: 
                   10896: =item *
                   10897: 
                   10898: modify_student_enrollment
                   10899: 
                   10900: Change a students enrollment status in a class.  The environment variable
                   10901: 'role.request.course' must be defined for this function to proceed.
                   10902: 
                   10903: Inputs:
                   10904: 
                   10905: =over 4
                   10906: 
                   10907: =item $udom, students domain
                   10908: 
                   10909: =item $uname, students name
                   10910: 
                   10911: =item $uid, students user id
                   10912: 
                   10913: =item $first, students first name
                   10914: 
                   10915: =item $middle
                   10916: 
                   10917: =item $last
                   10918: 
                   10919: =item $gene
                   10920: 
                   10921: =item $usec
                   10922: 
                   10923: =item $end
                   10924: 
                   10925: =item $start
                   10926: 
1.957     raeburn  10927: =item $type
                   10928: 
                   10929: =item $locktype
                   10930: 
                   10931: =item $cid
                   10932: 
                   10933: =item $selfenroll
                   10934: 
                   10935: =item $context
                   10936: 
1.297     matthew  10937: =back
                   10938: 
1.191     harris41 10939: 
                   10940: =item *
                   10941: 
1.243     albertel 10942: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10943: custom role; give a custom role to a user for the level given by URL.  Specify
                   10944: name and domain of role author, and role name
1.191     harris41 10945: 
                   10946: =item *
                   10947: 
1.243     albertel 10948: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10949: 
                   10950: =item *
                   10951: 
1.243     albertel 10952: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10953: 
                   10954: =back
                   10955: 
                   10956: =head2 Course Infomation
                   10957: 
                   10958: =over 4
1.191     harris41 10959: 
                   10960: =item *
                   10961: 
1.631     albertel 10962: coursedescription($courseid) : returns a hash of information about the
                   10963: specified course id, including all environment settings for the
                   10964: course, the description of the course will be in the hash under the
                   10965: key 'description'
1.191     harris41 10966: 
                   10967: =item *
                   10968: 
1.624     albertel 10969: resdata($name,$domain,$type,@which) : request for current parameter
                   10970: setting for a specific $type, where $type is either 'course' or 'user',
                   10971: @what should be a list of parameters to ask about. This routine caches
                   10972: answers for 5 minutes.
1.243     albertel 10973: 
1.877     foxr     10974: =item *
                   10975: 
                   10976: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10977: data base, returning a hash that is keyed by the resource name and has
                   10978: values that are the resource value.  I believe that the timestamps and
                   10979: versions are also returned.
                   10980: 
                   10981: 
1.243     albertel 10982: =back
                   10983: 
                   10984: =head2 Course Modification
                   10985: 
                   10986: =over 4
1.191     harris41 10987: 
                   10988: =item *
                   10989: 
1.243     albertel 10990: writecoursepref($courseid,%prefs) : write preferences (environment
                   10991: database) for a course
1.191     harris41 10992: 
                   10993: =item *
                   10994: 
1.1011    raeburn  10995: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10996: 
                   10997: =item *
                   10998: 
1.1038    raeburn  10999: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11000: 
                   11001: =back
                   11002: 
                   11003: =head2 Resource Subroutines
                   11004: 
                   11005: =over 4
1.191     harris41 11006: 
                   11007: =item *
                   11008: 
1.243     albertel 11009: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11010: 
                   11011: =item *
                   11012: 
1.243     albertel 11013: repcopy($filename) : subscribes to the requested file, and attempts to
                   11014: replicate from the owning library server, Might return
1.607     raeburn  11015: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11016: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11017: resource. Expects the local filesystem pathname
                   11018: (/home/httpd/html/res/....)
                   11019: 
                   11020: =back
                   11021: 
                   11022: =head2 Resource Information
                   11023: 
                   11024: =over 4
1.191     harris41 11025: 
                   11026: =item *
                   11027: 
1.243     albertel 11028: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11029: a vairety of different possible values, $varname should be a request
                   11030: string, and the other parameters can be used to specify who and what
                   11031: one is asking about.
                   11032: 
                   11033: Possible values for $varname are environment.lastname (or other item
                   11034: from the envirnment hash), user.name (or someother aspect about the
                   11035: user), resource.0.maxtries (or some other part and parameter of a
                   11036: resource)
1.204     albertel 11037: 
                   11038: =item *
                   11039: 
1.243     albertel 11040: directcondval($number) : get current value of a condition; reads from a state
                   11041: string
1.204     albertel 11042: 
                   11043: =item *
                   11044: 
1.243     albertel 11045: condval($condidx) : value of condition index based on state
1.204     albertel 11046: 
                   11047: =item *
                   11048: 
1.243     albertel 11049: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11050: resource's metadata, $what should be either a specific key, or either
                   11051: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11052: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11053: 
                   11054: this function automatically caches all requests
1.191     harris41 11055: 
                   11056: =item *
                   11057: 
1.243     albertel 11058: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11059: network of library servers; returns file handle of where SQL and regex results
                   11060: will be stored for query
1.191     harris41 11061: 
                   11062: =item *
                   11063: 
1.243     albertel 11064: symbread($filename) : return symbolic list entry (filename argument optional);
                   11065: returns the data handle
1.191     harris41 11066: 
                   11067: =item *
                   11068: 
1.243     albertel 11069: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11070: a possible symb for the URL in $thisfn, and if is an encryypted
                   11071: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11072: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11073: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11074: 
1.191     harris41 11075: 
                   11076: =item *
                   11077: 
1.243     albertel 11078: symbclean($symb) : removes versions numbers from a symb, returns the
                   11079: cleaned symb
1.191     harris41 11080: 
                   11081: =item *
                   11082: 
1.243     albertel 11083: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11084: course map, user must be in a course for it to work.
1.191     harris41 11085: 
                   11086: =item *
                   11087: 
1.243     albertel 11088: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11089: 
                   11090: =item *
                   11091: 
1.243     albertel 11092: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11093: a random seed, all arguments are optional, if they aren't sent it uses the
                   11094: environment to derive them. Note: if symb isn't sent and it can't get one
                   11095: from &symbread it will use the current time as its return value
1.191     harris41 11096: 
                   11097: =item *
                   11098: 
1.243     albertel 11099: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11100: unfakeable, receipt
1.191     harris41 11101: 
                   11102: =item *
                   11103: 
1.620     albertel 11104: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11105: 
                   11106: =item *
                   11107: 
1.243     albertel 11108: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11109: 
                   11110: =item *
                   11111: 
1.243     albertel 11112: 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 11113: 
                   11114: =item *
                   11115: 
1.243     albertel 11116: 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 11117: 
                   11118: =item *
                   11119: 
1.243     albertel 11120: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11121: 
                   11122: =item *
                   11123: 
1.243     albertel 11124: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11125: forcing spreadsheet to reevaluate the resource scores next time.
                   11126: 
                   11127: =back
                   11128: 
                   11129: =head2 Storing/Retreiving Data
                   11130: 
                   11131: =over 4
1.191     harris41 11132: 
                   11133: =item *
                   11134: 
1.243     albertel 11135: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11136: for this url; hashref needs to be given and should be a \%hashname; the
                   11137: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11138: be derived from the env
1.191     harris41 11139: 
                   11140: =item *
                   11141: 
1.243     albertel 11142: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11143: uses critical subroutine
1.191     harris41 11144: 
                   11145: =item *
                   11146: 
1.243     albertel 11147: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11148: all args are optional
1.191     harris41 11149: 
                   11150: =item *
                   11151: 
1.717     albertel 11152: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11153: dumps the complete (or key matching regexp) namespace into a hash
                   11154: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11155: normally &store()ed into
                   11156: 
                   11157: $range should be either an integer '100' (give me the first 100
                   11158:                                            matching records)
                   11159:               or be  two integers sperated by a - with no spaces
                   11160:                  '30-50' (give me the 30th through the 50th matching
                   11161:                           records)
                   11162: 
                   11163: 
                   11164: =item *
                   11165: 
                   11166: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11167: replaces a &store() version of data with a replacement set of data
                   11168: for a particular resource in a namespace passed in the $storehash hash 
                   11169: reference
                   11170: 
                   11171: =item *
                   11172: 
1.243     albertel 11173: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11174: works very similar to store/cstore, but all data is stored in a
                   11175: temporary location and can be reset using tmpreset, $storehash should
                   11176: be a hash reference, returns nothing on success
1.191     harris41 11177: 
                   11178: =item *
                   11179: 
1.243     albertel 11180: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11181: similar to restore, but all data is stored in a temporary location and
                   11182: can be reset using tmpreset. Returns a hash of values on success,
                   11183: error string otherwise.
1.191     harris41 11184: 
                   11185: =item *
                   11186: 
1.243     albertel 11187: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11188: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11189: 
                   11190: =item *
                   11191: 
1.243     albertel 11192: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11193: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11194: 
                   11195: =item *
                   11196: 
1.243     albertel 11197: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11198: namesp ($udom and $uname are optional)
1.191     harris41 11199: 
                   11200: =item *
                   11201: 
1.702     albertel 11202: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11203: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11204: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11205: 
1.702     albertel 11206: $range should be either an integer '100' (give me the first 100
                   11207:                                            matching records)
                   11208:               or be  two integers sperated by a - with no spaces
                   11209:                  '30-50' (give me the 30th through the 50th matching
                   11210:                           records)
1.449     matthew  11211: =item *
                   11212: 
                   11213: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11214: $store can be a scalar, an array reference, or if the amount to be 
                   11215: incremented is > 1, a hash reference.
                   11216: 
                   11217: ($udom and $uname are optional)
1.191     harris41 11218: 
                   11219: =item *
                   11220: 
1.243     albertel 11221: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11222: ($udom and $uname are optional)
1.191     harris41 11223: 
                   11224: =item *
                   11225: 
1.243     albertel 11226: cput($namespace,$storehash,$udom,$uname) : critical put
                   11227: ($udom and $uname are optional)
1.191     harris41 11228: 
                   11229: =item *
                   11230: 
1.748     albertel 11231: newput($namespace,$storehash,$udom,$uname) :
                   11232: 
                   11233: Attempts to store the items in the $storehash, but only if they don't
                   11234: currently exist, if this succeeds you can be certain that you have 
                   11235: successfully created a new key value pair in the $namespace db.
                   11236: 
                   11237: 
                   11238: Args:
                   11239:  $namespace: name of database to store values to
                   11240:  $storehash: hashref to store to the db
                   11241:  $udom: (optional) domain of user containing the db
                   11242:  $uname: (optional) name of user caontaining the db
                   11243: 
                   11244: Returns:
                   11245:  'ok' -> succeeded in storing all keys of $storehash
                   11246:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11247:                         least <key> already existed in the db (other
                   11248:                         requested keys may also already exist)
1.967     bisitz   11249:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11250:  'con_lost' -> unable to contact request server
                   11251:  'refused' -> action was not allowed by remote machine
                   11252: 
                   11253: 
                   11254: =item *
                   11255: 
1.243     albertel 11256: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11257: reference filled in from namesp (encrypts the return communication)
                   11258: ($udom and $uname are optional)
1.191     harris41 11259: 
                   11260: =item *
                   11261: 
1.243     albertel 11262: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11263: critical subroutine
                   11264: 
1.806     raeburn  11265: =item *
                   11266: 
1.860     raeburn  11267: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11268: array reference filled in from namespace found in domain level on either
                   11269: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11270: 
                   11271: =item *
                   11272: 
1.860     raeburn  11273: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11274: domain level either on specified domain server ($uhome) or primary domain 
                   11275: server ($udom and $uhome are optional)
1.806     raeburn  11276: 
1.943     raeburn  11277: =item * 
                   11278: 
                   11279: get_domain_defaults($target_domain) : returns hash with defaults for
                   11280: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11281: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11282: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11283: Values are retrieved from cache (if current), or from domain's configuration.db
                   11284: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11285: or lonTabs/domain.tab. 
                   11286: 
                   11287: %domdefaults = &get_auth_defaults($target_domain);
                   11288: 
1.243     albertel 11289: =back
                   11290: 
                   11291: =head2 Network Status Functions
                   11292: 
                   11293: =over 4
1.191     harris41 11294: 
                   11295: =item *
                   11296: 
                   11297: dirlist($uri) : return directory list based on URI
                   11298: 
                   11299: =item *
                   11300: 
1.243     albertel 11301: spareserver() : find server with least workload from spare.tab
                   11302: 
1.986     foxr     11303: 
                   11304: =item *
                   11305: 
                   11306: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11307: if there is no corresponding loncapa host.
                   11308: 
1.243     albertel 11309: =back
                   11310: 
1.986     foxr     11311: 
1.243     albertel 11312: =head2 Apache Request
                   11313: 
                   11314: =over 4
1.191     harris41 11315: 
                   11316: =item *
                   11317: 
1.243     albertel 11318: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11319: localhost, posts hash
                   11320: 
                   11321: =back
                   11322: 
                   11323: =head2 Data to String to Data
                   11324: 
                   11325: =over 4
1.191     harris41 11326: 
                   11327: =item *
                   11328: 
1.243     albertel 11329: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11330: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: hashref2str($hashref) : convert a hashref into a string complete with
                   11335: escaping and '=' and '&' separators, supports elements that are
                   11336: arrayrefs and hashrefs
1.191     harris41 11337: 
                   11338: =item *
                   11339: 
1.243     albertel 11340: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11341: with escaping and '&' separators, supports elements that are arrayrefs
                   11342: and hashrefs
1.191     harris41 11343: 
                   11344: =item *
                   11345: 
1.243     albertel 11346: str2hash($string) : convert string to hash using unescaping and
                   11347: splitting on '=' and '&', supports elements that are arrayrefs and
                   11348: hashrefs
1.191     harris41 11349: 
                   11350: =item *
                   11351: 
1.243     albertel 11352: str2array($string) : convert string to hash using unescaping and
                   11353: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11354: 
                   11355: =back
                   11356: 
                   11357: =head2 Logging Routines
                   11358: 
                   11359: =over 4
                   11360: 
                   11361: These routines allow one to make log messages in the lonnet.log and
                   11362: lonnet.perm logfiles.
1.191     harris41 11363: 
                   11364: =item *
                   11365: 
1.243     albertel 11366: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11367: 
                   11368: =item *
                   11369: 
1.243     albertel 11370: logthis() : append message to the normal lonnet.log file, it gets
                   11371: preiodically rolled over and deleted.
1.191     harris41 11372: 
                   11373: =item *
                   11374: 
1.243     albertel 11375: logperm() : append a permanent message to lonnet.perm.log, this log
                   11376: file never gets deleted by any automated portion of the system, only
                   11377: messages of critical importance should go in here.
                   11378: 
                   11379: =back
                   11380: 
                   11381: =head2 General File Helper Routines
                   11382: 
                   11383: =over 4
1.191     harris41 11384: 
                   11385: =item *
                   11386: 
1.481     raeburn  11387: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11388: (a) files in /uploaded
                   11389:   (i) If a local copy of the file exists - 
                   11390:       compares modification date of local copy with last-modified date for 
                   11391:       definitive version stored on home server for course. If local copy is 
                   11392:       stale, requests a new version from the home server and stores it. 
                   11393:       If the original has been removed from the home server, then local copy 
                   11394:       is unlinked.
                   11395:   (ii) If local copy does not exist -
                   11396:       requests the file from the home server and stores it. 
                   11397:   
                   11398:   If $caller is 'uploadrep':  
                   11399:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11400:     for request for files originally uploaded via DOCS. 
                   11401:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11402:   
                   11403:   Otherwise:
                   11404:      This indicates a call from the content generation phase of the request.
                   11405:      -  returns the entire contents of the file or -1.
                   11406:      
                   11407: (b) files in /res
                   11408:    - returns the entire contents of a file or -1; 
                   11409:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11410: 
1.712     albertel 11411: 
                   11412: =item *
                   11413: 
                   11414: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11415:                   reference
                   11416: 
                   11417: returns either a stat() list of data about the file or an empty list
                   11418: if the file doesn't exist or couldn't find out about it (connection
                   11419: problems or user unknown)
                   11420: 
1.191     harris41 11421: =item *
                   11422: 
1.243     albertel 11423: filelocation($dir,$file) : returns file system location of a file
                   11424: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11425: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11426: and a file of ../bob will become /a/bob)
1.191     harris41 11427: 
                   11428: =item *
                   11429: 
                   11430: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11431: filelocation except for hrefs
                   11432: 
                   11433: =item *
                   11434: 
                   11435: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11436: 
1.243     albertel 11437: =back
                   11438: 
1.608     albertel 11439: =head2 Usererfile file routines (/uploaded*)
                   11440: 
                   11441: =over 4
                   11442: 
                   11443: =item *
                   11444: 
                   11445: userfileupload(): main rotine for putting a file in a user or course's
                   11446:                   filespace, arguments are,
                   11447: 
1.620     albertel 11448:  formname - required - this is the name of the element in $env where the
1.608     albertel 11449:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11450:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11451:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11452:  context - if coursedoc, store the file in the course of the active role
                   11453:              of the current user;
                   11454:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11455:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11456:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11457:          if undefined, it will be placed in "unknown"
                   11458: 
                   11459:  (This routine calls clean_filename() to remove any dangerous
                   11460:  characters from the filename, and then calls finuserfileupload() to
                   11461:  complete the transaction)
                   11462: 
                   11463:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11464:  and /adm/notfound.html if unsuccessful
                   11465: 
                   11466: =item *
                   11467: 
                   11468: clean_filename(): routine for cleaing a filename up for storage in
                   11469:                  userfile space, argument is:
                   11470: 
                   11471:  filename - proposed filename
                   11472: 
                   11473: returns: the new clean filename
                   11474: 
                   11475: =item *
                   11476: 
1.1056.4.13  raeburn  11477: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11478: userspace, probably shouldn't be called directly
                   11479: 
                   11480:   docuname: username or courseid of destination for the file
                   11481:   docudom: domain of user/course of destination for the file
                   11482:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11483:   fname: filename (including subdirectories) for the file
                   11484:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11485:   allfiles: reference to hash used to store objects found by parser
                   11486:   codebase: reference to hash used for codebases of java objects found by parser
                   11487:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11488:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11489:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11490:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11491:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11492:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.608     albertel 11493: 
                   11494:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11495:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11496:  was 'overwrite').
                   11497: 
1.608     albertel 11498: 
                   11499: =item *
                   11500: 
                   11501: renameuserfile(): renames an existing userfile to a new name
                   11502: 
                   11503:   Args:
                   11504:    docuname: username or courseid of destination for the file
                   11505:    docudom: domain of user/course of destination for the file
                   11506:    old: current file name (including any subdirs under userfiles)
                   11507:    new: desired file name (including any subdirs under userfiles)
                   11508: 
                   11509: =item *
                   11510: 
                   11511: mkdiruserfile(): creates a directory is a userfiles dir
                   11512: 
                   11513:   Args:
                   11514:    docuname: username or courseid of destination for the file
                   11515:    docudom: domain of user/course of destination for the file
                   11516:    dir: dir to create (including any subdirs under userfiles)
                   11517: 
                   11518: =item *
                   11519: 
                   11520: removeuserfile(): removes a file that exists in userfiles
                   11521: 
                   11522:   Args:
                   11523:    docuname: username or courseid of destination for the file
                   11524:    docudom: domain of user/course of destination for the file
                   11525:    fname: filname to delete (including any subdirs under userfiles)
                   11526: 
                   11527: =item *
                   11528: 
                   11529: removeuploadedurl(): convience function for removeuserfile()
                   11530: 
                   11531:   Args:
                   11532:    url:  a full /uploaded/... url to delete
                   11533: 
1.747     albertel 11534: =item * 
                   11535: 
                   11536: get_portfile_permissions():
                   11537:   Args:
                   11538:     domain: domain of user or course contain the portfolio files
                   11539:     user: name of user or num of course contain the portfolio files
                   11540:   Returns:
                   11541:     hashref of a dump of the proper file_permissions.db
                   11542:    
                   11543: 
                   11544: =item * 
                   11545: 
                   11546: get_access_controls():
                   11547: 
                   11548: Args:
                   11549:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11550:   group: (optional) the group you want the files associated with
                   11551:   file: (optional) the file you want access info on
                   11552: 
                   11553: Returns:
1.749     raeburn  11554:     a hash (keys are file names) of hashes containing
                   11555:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11556:         values are XML containing access control settings (see below) 
1.747     albertel 11557: 
                   11558: Internal notes:
                   11559: 
1.749     raeburn  11560:  access controls are stored in file_permissions.db as key=value pairs.
                   11561:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11562:         where scope -> public,guest,course,group,domains or users.
                   11563:               end -> UNIX time for end of access (0 -> no end date)
                   11564:               start -> UNIX time for start of access
                   11565: 
                   11566:     value -> XML description of access control
                   11567:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11568:             <start></start>
                   11569:             <end></end>
                   11570: 
                   11571:             <password></password>  for scope type = guest
                   11572: 
                   11573:             <domain></domain>     for scope type = course or group
                   11574:             <number></number>
                   11575:             <roles id="">
                   11576:              <role></role>
                   11577:              <access></access>
                   11578:              <section></section>
                   11579:              <group></group>
                   11580:             </roles>
                   11581: 
                   11582:             <dom></dom>         for scope type = domains
                   11583: 
                   11584:             <users>             for scope type = users
                   11585:              <user>
                   11586:               <uname></uname>
                   11587:               <udom></udom>
                   11588:              </user>
                   11589:             </users>
                   11590:            </scope> 
                   11591:               
                   11592:  Access data is also aggregated for each file in an additional key=value pair:
                   11593:  key -> path to file/file_name\0accesscontrol 
                   11594:  value -> reference to hash
                   11595:           hash contains key = value pairs
                   11596:           where key = uniqueID:scope_end_start
                   11597:                 value = UNIX time record was last updated
                   11598: 
                   11599:           Used to improve speed of look-ups of access controls for each file.  
                   11600:  
                   11601:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11602: 
                   11603: modify_access_controls():
                   11604: 
                   11605: Modifies access controls for a portfolio file
                   11606: Args
                   11607: 1. file name
                   11608: 2. reference to hash of required changes,
                   11609: 3. domain
                   11610: 4. username
                   11611:   where domain,username are the domain of the portfolio owner 
                   11612:   (either a user or a course) 
                   11613: 
                   11614: Returns:
                   11615: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11616: 2. result of deletions ('ok' or 'error', with error message).
                   11617: 3. reference to hash of any new or updated access controls.
                   11618: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11619:    key = integer (inbound ID)
                   11620:    value = uniqueID  
1.747     albertel 11621: 
1.608     albertel 11622: =back
                   11623: 
1.243     albertel 11624: =head2 HTTP Helper Routines
                   11625: 
                   11626: =over 4
                   11627: 
1.191     harris41 11628: =item *
                   11629: 
                   11630: escape() : unpack non-word characters into CGI-compatible hex codes
                   11631: 
                   11632: =item *
                   11633: 
                   11634: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11635: 
1.243     albertel 11636: =back
                   11637: 
                   11638: =head1 PRIVATE SUBROUTINES
                   11639: 
                   11640: =head2 Underlying communication routines (Shouldn't call)
                   11641: 
                   11642: =over 4
                   11643: 
                   11644: =item *
                   11645: 
                   11646: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11647: 
                   11648: =item *
                   11649: 
                   11650: reply() : uses subreply to send a message to remote machine, logs all failures
                   11651: 
                   11652: =item *
                   11653: 
                   11654: critical() : passes a critical message to another server; if cannot
                   11655: get through then place message in connection buffer directory and
                   11656: returns con_delayed, if incapable of saving message, returns
                   11657: con_failed
                   11658: 
                   11659: =item *
                   11660: 
                   11661: reconlonc() : tries to reconnect lonc client processes.
                   11662: 
                   11663: =back
                   11664: 
                   11665: =head2 Resource Access Logging
                   11666: 
                   11667: =over 4
                   11668: 
                   11669: =item *
                   11670: 
                   11671: flushcourselogs() : flush (save) buffer logs and access logs
                   11672: 
                   11673: =item *
                   11674: 
                   11675: courselog($what) : save message for course in hash
                   11676: 
                   11677: =item *
                   11678: 
                   11679: courseacclog($what) : save message for course using &courselog().  Perform
                   11680: special processing for specific resource types (problems, exams, quizzes, etc).
                   11681: 
1.191     harris41 11682: =item *
                   11683: 
                   11684: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11685: as a PerlChildExitHandler
1.243     albertel 11686: 
                   11687: =back
                   11688: 
                   11689: =head2 Other
                   11690: 
                   11691: =over 4
                   11692: 
                   11693: =item *
                   11694: 
                   11695: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11696: 
                   11697: =back
                   11698: 
                   11699: =cut
1.877     foxr     11700: 

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