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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.23! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.22 2011/03/04 02:02:37 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.1056.4.23! raeburn   755:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
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);
1.1056.4.23! raeburn   761:     if (($udom ne '') && (&domain($udom) ne '')) {
        !           762:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8  raeburn   763:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23! raeburn   764:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8  raeburn   765:         $remotesessions = $udomdefaults{'remotesessions'};
                    766:     }
1.784     albertel  767:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   768:         if ($uint_dom) {
1.1056.4.23! raeburn   769:             next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
        !           770:                                          $try_server));
1.1056.4.8  raeburn   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) {
1.1056.4.23! raeburn   781:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
        !           782:                                              $try_server));
1.1056.4.8  raeburn   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.
1.1056.4.16  raeburn  2203: #        reference to scalar to accommodate mime type determined
                   2204: #          from File::MMagic if $parser = parse.
1.637     raeburn  2205: #
1.485     raeburn  2206: # output: url to file (if action was uploaddoc), 
                   2207: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2208: #
1.478     albertel 2209: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2210: # course.
1.477     raeburn  2211: #
1.478     albertel 2212: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2213: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2214: #          course's home server.
1.477     raeburn  2215: #
1.478     albertel 2216: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2217: #          be copied from $source (current location) to 
                   2218: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2219: #         and will then be copied to
                   2220: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2221: #         course's home server.
1.485     raeburn  2222: #
1.481     raeburn  2223: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2224: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2225: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2226: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2227: #         in course's home server.
1.637     raeburn  2228: #
1.477     raeburn  2229: 
                   2230: sub process_coursefile {
1.1056.4.16  raeburn  2231:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2232:         $mimetype)=@_;
1.477     raeburn  2233:     my $fetchresult;
1.638     albertel 2234:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2235:     if ($action eq 'propagate') {
1.638     albertel 2236:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2237: 			     $home);
1.481     raeburn  2238:     } else {
1.477     raeburn  2239:         my $fpath = '';
                   2240:         my $fname = $file;
1.478     albertel 2241:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2242:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2243:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2244:         if ($action eq 'copy') {
                   2245:             if ($source eq '') {
                   2246:                 $fetchresult = 'no source file';
                   2247:                 return $fetchresult;
                   2248:             } else {
                   2249:                 my $destination = $filepath.'/'.$fname;
                   2250:                 rename($source,$destination);
                   2251:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2252:                                  $home);
1.481     raeburn  2253:             }
                   2254:         } elsif ($action eq 'uploaddoc') {
                   2255:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2256:             print $fh $env{'form.'.$source};
1.481     raeburn  2257:             close($fh);
1.637     raeburn  2258:             if ($parser eq 'parse') {
1.1024    raeburn  2259:                 my $mm = new File::MMagic;
1.1056.4.16  raeburn  2260:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2261:                 if ($type eq 'text/html') {
1.1024    raeburn  2262:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2263:                     unless ($parse_result eq 'ok') {
                   2264:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2265:                     }
1.637     raeburn  2266:                 }
1.1056.4.16  raeburn  2267:                 if (ref($mimetype)) {
                   2268:                     $$mimetype = $type;
                   2269:                 }
1.637     raeburn  2270:             }
1.477     raeburn  2271:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2272:                                  $home);
1.481     raeburn  2273:             if ($fetchresult eq 'ok') {
                   2274:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2275:             } else {
                   2276:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2277:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2278:                 return '/adm/notfound.html';
                   2279:             }
1.477     raeburn  2280:         }
                   2281:     }
1.485     raeburn  2282:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2283:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2284:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2285:     }
                   2286:     return $fetchresult;
                   2287: }
                   2288: 
1.637     raeburn  2289: sub build_filepath {
                   2290:     my ($fpath) = @_;
                   2291:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2292:     unless ($fpath eq '') {
                   2293:         my @parts=split('/',$fpath);
                   2294:         foreach my $part (@parts) {
                   2295:             $filepath.= '/'.$part;
                   2296:             if ((-e $filepath)!=1) {
                   2297:                 mkdir($filepath,0777);
                   2298:             }
                   2299:         }
                   2300:     }
                   2301:     return $filepath;
                   2302: }
                   2303: 
                   2304: sub store_edited_file {
1.638     albertel 2305:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2306:     my $file = $primary_url;
                   2307:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2308:     my $fpath = '';
                   2309:     my $fname = $file;
                   2310:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2311:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2312:     my $filepath = &build_filepath($fpath);
                   2313:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2314:     print $fh $content;
                   2315:     close($fh);
1.638     albertel 2316:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2317:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2318: 			  $home);
1.637     raeburn  2319:     if ($$fetchresult eq 'ok') {
                   2320:         return '/uploaded/'.$fpath.'/'.$fname;
                   2321:     } else {
1.638     albertel 2322:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2323: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2324:         return '/adm/notfound.html';
                   2325:     }
                   2326: }
                   2327: 
1.531     albertel 2328: sub clean_filename {
1.831     albertel 2329:     my ($fname,$args)=@_;
1.315     www      2330: # Replace Windows backslashes by forward slashes
1.257     www      2331:     $fname=~s/\\/\//g;
1.831     albertel 2332:     if (!$args->{'keep_path'}) {
                   2333:         # Get rid of everything but the actual filename
                   2334: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2335:     }
1.315     www      2336: # Replace spaces by underscores
                   2337:     $fname=~s/\s+/\_/g;
                   2338: # Replace all other weird characters by nothing
1.831     albertel 2339:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2340: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2341: # numbers
                   2342:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2343:     return $fname;
                   2344: }
1.1051    raeburn  2345: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2346: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2347: # image with the same aspect ratio as the original, but with dimensions which do 
                   2348: # not exceed $resizewidth and $resizeheight.
                   2349:  
1.984     neumanie 2350: sub resizeImage {
1.1051    raeburn  2351:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2352:     my $ima = Image::Magick->new;
                   2353:     my $resized;
                   2354:     if (-e $img_path) {
                   2355:         $ima->Read($img_path);
                   2356:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2357:             my $width = $ima->Get('width');
                   2358:             my $height = $ima->Get('height');
                   2359:             if ($width > $resizewidth) {
                   2360: 	        my $factor = $width/$resizewidth;
                   2361:                 my $newheight = $height/$factor;
                   2362:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2363:                 $resized = 1;
                   2364:             }
                   2365:         }
                   2366:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2367:             my $width = $ima->Get('width');
                   2368:             my $height = $ima->Get('height');
                   2369:             if ($height > $resizeheight) {
                   2370:                 my $factor = $height/$resizeheight;
                   2371:                 my $newwidth = $width/$factor;
                   2372:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2373:                 $resized = 1;
                   2374:             }
                   2375:         }
                   2376:         if ($resized) {
                   2377:             $ima->Write($img_path);
                   2378:         }
                   2379:     }
                   2380:     return;
1.977     amueller 2381: }
                   2382: 
1.608     albertel 2383: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2384: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2385: #                    the desired filename is in $env{"form.$formname.filename"}
                   2386: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2387: #                                    canceloverwrite, or ''.
                   2388: #                   if 'coursedoc': upload to the current course
                   2389: #                   if 'existingfile': write file to tmp/overwrites directory
                   2390: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2391: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2392: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2393: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2394: #        $allfiles - reference to hash for embedded objects
                   2395: #        $codebase - reference to hash for codebase of java objects
                   2396: #        $desuname - username for permanent storage of uploaded file
                   2397: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2398: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2399: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2400: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2401: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16  raeburn  2402: #        $mimetype - reference to scalar to accommodate mime type determined
                   2403: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2404: # 
1.686     albertel 2405: # output: url of file in userspace, or error: <message> 
                   2406: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2407: 
1.531     albertel 2408: sub userfileupload {
1.1056.4.13  raeburn  2409:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16  raeburn  2410:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2411:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2412:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2413:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2414:     # See if there is anything left
1.257     www      2415:     unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13  raeburn  2416:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2417:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2418:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2419:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2420:         my $now = time;
1.1056.4.13  raeburn  2421:         my $filepath;
                   2422:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2423:              $filepath = 'tmp/helprequests/'.$now;
                   2424:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2425:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2426:                          '_'.$env{'user.domain'}.'/pending';
                   2427:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2428:             my ($docuname,$docudom);
                   2429:             if ($destudom) {
                   2430:                 $docudom = $destudom;
                   2431:             } else {
                   2432:                 $docudom = $env{'user.domain'};
                   2433:             }
                   2434:             if ($destuname) {
                   2435:                 $docuname = $destuname;
                   2436:             } else {
                   2437:                 $docuname = $env{'user.name'};
                   2438:             }
                   2439:             if (exists($env{'form.group'})) {
                   2440:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2441:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2442:             }
                   2443:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2444:             if ($context eq 'canceloverwrite') {
                   2445:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2446:                 if (-e  $tempfile) {
                   2447:                     my @info = stat($tempfile);
                   2448:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2449:                         unlink($tempfile);
                   2450:                     }
                   2451:                 }
                   2452:                 return;
1.523     raeburn  2453:             }
                   2454:         }
1.1056.4.13  raeburn  2455:         # Create the directory if not present
1.741     raeburn  2456:         my @parts=split(/\//,$filepath);
                   2457:         my $fullpath = $perlvar{'lonDaemons'};
                   2458:         for (my $i=0;$i<@parts;$i++) {
                   2459:             $fullpath .= '/'.$parts[$i];
                   2460:             if ((-e $fullpath)!=1) {
                   2461:                 mkdir($fullpath,0777);
                   2462:             }
                   2463:         }
                   2464:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2465:         print $fh $env{'form.'.$formname};
                   2466:         close($fh);
1.1056.4.13  raeburn  2467:         if ($context eq 'existingfile') {
                   2468:             my @info = stat($fullpath.'/'.$fname);
                   2469:             return ($fullpath.'/'.$fname,$info[9]);
                   2470:         } else {
                   2471:             return $fullpath.'/'.$fname;
                   2472:         }
1.523     raeburn  2473:     }
1.995     raeburn  2474:     if ($subdir eq 'scantron') {
                   2475:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14  raeburn  2476:     } else {
1.995     raeburn  2477:         $fname="$subdir/$fname";
                   2478:     }
1.1056.4.13  raeburn  2479:     if ($context eq 'coursedoc') {
1.638     albertel 2480: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2481: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2482:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2483:             return &finishuserfileupload($docuname,$docudom,
                   2484: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2485: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2486:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2487:         } else {
1.620     albertel 2488:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2489:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2490: 				       $fname,$formname,$parser,
1.1056.4.16  raeburn  2491: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2492:         }
1.719     banghart 2493:     } elsif (defined($destuname)) {
                   2494:         my $docuname=$destuname;
                   2495:         my $docudom=$destudom;
1.860     raeburn  2496: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2497: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2498:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2499:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2500:     } else {
1.638     albertel 2501:         my $docuname=$env{'user.name'};
                   2502:         my $docudom=$env{'user.domain'};
1.714     raeburn  2503:         if (exists($env{'form.group'})) {
                   2504:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2505:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2506:         }
1.860     raeburn  2507: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2508: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2509:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2510:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2511:     }
1.271     www      2512: }
                   2513: 
                   2514: sub finishuserfileupload {
1.860     raeburn  2515:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16  raeburn  2516:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2517:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2518:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2519:   
1.860     raeburn  2520:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2521:     $file=$fname;
                   2522:     if ($fname=~m|/|) {
                   2523:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2524: 	$path.=$fnamepath.'/';
                   2525:     }
1.259     www      2526:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2527:     my $count;
                   2528:     for ($count=4;$count<=$#parts;$count++) {
                   2529:         $filepath.="/$parts[$count]";
                   2530:         if ((-e $filepath)!=1) {
                   2531: 	    mkdir($filepath,0777);
                   2532:         }
                   2533:     }
1.984     neumanie 2534: 
1.258     www      2535: # Save the file
                   2536:     {
1.701     albertel 2537: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2538: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2539: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2540: 	    return '/adm/notfound.html';
                   2541: 	}
1.1056.4.13  raeburn  2542:         if ($context eq 'overwrite') {
                   2543:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2544:             my $target = $filepath.'/'.$file;
                   2545:             if (-e $source) {
                   2546:                 my @info = stat($source);
                   2547:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2548:                     unless (&File::Copy::move($source,$target)) {
                   2549:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2550:                         return "Moving from $source failed";
                   2551:                     }
                   2552:                 } else {
                   2553:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2554:                 }
                   2555:             } else {
                   2556:                 return "Temporary file: $source missing";
                   2557:             }
                   2558: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2559: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2560: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2561: 	    return '/adm/notfound.html';
                   2562: 	}
1.570     albertel 2563: 	close(FH);
1.1051    raeburn  2564:         if ($resizewidth && $resizeheight) {
                   2565:             my $mm = new File::MMagic;
                   2566:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2567:             if ($mime_type =~ m{^image/}) {
                   2568: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2569:             }  
1.977     amueller 2570: 	}
1.258     www      2571:     }
1.637     raeburn  2572:     if ($parser eq 'parse') {
1.1024    raeburn  2573:         my $mm = new File::MMagic;
1.1056.4.16  raeburn  2574:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2575:         if ($type eq 'text/html') {
1.1024    raeburn  2576:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2577:                                                        $allfiles,$codebase);
                   2578:             unless ($parse_result eq 'ok') {
                   2579:                 &logthis('Failed to parse '.$filepath.$file.
                   2580: 	   	         ' for embedded media: '.$parse_result); 
                   2581:             }
1.637     raeburn  2582:         }
1.1056.4.16  raeburn  2583:         if (ref($mimetype)) {
                   2584:             $$mimetype = $type;
                   2585:         }
1.637     raeburn  2586:     }
1.860     raeburn  2587:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2588:         my $input = $filepath.'/'.$file;
                   2589:         my $output = $filepath.'/'.'tn-'.$file;
                   2590:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2591:         system("convert -sample $thumbsize $input $output");
                   2592:         if (-e $filepath.'/'.'tn-'.$file) {
                   2593:             $fetchthumb  = 1; 
                   2594:         }
                   2595:     }
1.858     raeburn  2596:  
1.259     www      2597: # Notify homeserver to grep it
                   2598: #
1.984     neumanie 2599:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2600:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2601:     if ($fetchresult eq 'ok') {
1.860     raeburn  2602:         if ($fetchthumb) {
                   2603:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2604:             if ($thumbresult ne 'ok') {
                   2605:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2606:                          $docuhome.': '.$thumbresult);
                   2607:             }
                   2608:         }
1.259     www      2609: #
1.258     www      2610: # Return the URL to it
1.494     albertel 2611:         return '/uploaded/'.$path.$file;
1.263     www      2612:     } else {
1.494     albertel 2613:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2614: 		 ': '.$fetchresult);
1.263     www      2615:         return '/adm/notfound.html';
1.858     raeburn  2616:     }
1.493     albertel 2617: }
                   2618: 
1.637     raeburn  2619: sub extract_embedded_items {
1.961     raeburn  2620:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2621:     my @state = ();
                   2622:     my %javafiles = (
                   2623:                       codebase => '',
                   2624:                       code => '',
                   2625:                       archive => ''
                   2626:                     );
                   2627:     my %mediafiles = (
                   2628:                       src => '',
                   2629:                       movie => '',
                   2630:                      );
1.648     raeburn  2631:     my $p;
                   2632:     if ($content) {
                   2633:         $p = HTML::LCParser->new($content);
                   2634:     } else {
1.961     raeburn  2635:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2636:     }
1.641     albertel 2637:     while (my $t=$p->get_token()) {
1.640     albertel 2638: 	if ($t->[0] eq 'S') {
                   2639: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2640: 	    push(@state, $tagname);
1.648     raeburn  2641:             if (lc($tagname) eq 'allow') {
                   2642:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2643:             }
1.640     albertel 2644: 	    if (lc($tagname) eq 'img') {
                   2645: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2646: 	    }
1.886     albertel 2647: 	    if (lc($tagname) eq 'a') {
                   2648: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2649: 	    }
1.645     raeburn  2650:             if (lc($tagname) eq 'script') {
                   2651:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2652:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2653:                 } else {
                   2654:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2655:                 }
                   2656:             }
                   2657:             if (lc($tagname) eq 'link') {
                   2658:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2659:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2660:                 }
                   2661:             }
1.640     albertel 2662: 	    if (lc($tagname) eq 'object' ||
                   2663: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2664: 		foreach my $item (keys(%javafiles)) {
                   2665: 		    $javafiles{$item} = '';
                   2666: 		}
                   2667: 	    }
                   2668: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2669: 		my $name = lc($attr->{'name'});
                   2670: 		foreach my $item (keys(%javafiles)) {
                   2671: 		    if ($name eq $item) {
                   2672: 			$javafiles{$item} = $attr->{'value'};
                   2673: 			last;
                   2674: 		    }
                   2675: 		}
                   2676: 		foreach my $item (keys(%mediafiles)) {
                   2677: 		    if ($name eq $item) {
                   2678: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2679: 			last;
                   2680: 		    }
                   2681: 		}
                   2682: 	    }
                   2683: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2684: 		foreach my $item (keys(%javafiles)) {
                   2685: 		    if ($attr->{$item}) {
                   2686: 			$javafiles{$item} = $attr->{$item};
                   2687: 			last;
                   2688: 		    }
                   2689: 		}
                   2690: 		foreach my $item (keys(%mediafiles)) {
                   2691: 		    if ($attr->{$item}) {
                   2692: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2693: 			last;
                   2694: 		    }
                   2695: 		}
                   2696: 	    }
                   2697: 	} elsif ($t->[0] eq 'E') {
                   2698: 	    my ($tagname) = ($t->[1]);
                   2699: 	    if ($javafiles{'codebase'} ne '') {
                   2700: 		$javafiles{'codebase'} .= '/';
                   2701: 	    }  
                   2702: 	    if (lc($tagname) eq 'applet' ||
                   2703: 		lc($tagname) eq 'object' ||
                   2704: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2705: 		) {
                   2706: 		foreach my $item (keys(%javafiles)) {
                   2707: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2708: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2709: 			&add_filetype($allfiles,$file,$item);
                   2710: 		    }
                   2711: 		}
                   2712: 	    } 
                   2713: 	    pop @state;
                   2714: 	}
                   2715:     }
1.637     raeburn  2716:     return 'ok';
                   2717: }
                   2718: 
1.639     albertel 2719: sub add_filetype {
                   2720:     my ($allfiles,$file,$type)=@_;
                   2721:     if (exists($allfiles->{$file})) {
                   2722: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2723: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2724: 	}
                   2725:     } else {
                   2726: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2727:     }
                   2728: }
                   2729: 
1.493     albertel 2730: sub removeuploadedurl {
1.984     neumanie 2731:     my ($url)=@_;	
                   2732:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2733:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2734: }
                   2735: 
                   2736: sub removeuserfile {
                   2737:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2738:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2739:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2740:     if ($result eq 'ok') {	
1.798     raeburn  2741:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2742:             my $metafile = $fname.'.meta';
                   2743:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2744: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2745:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2746:             my $sqlresult = 
1.823     albertel 2747:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2748:                                         'portfolio_metadata',$group,
                   2749:                                         'delete');
1.798     raeburn  2750:         }
                   2751:     }
                   2752:     return $result;
1.257     www      2753: }
1.15      www      2754: 
1.530     albertel 2755: sub mkdiruserfile {
                   2756:     my ($docuname,$docudom,$dir)=@_;
                   2757:     my $home=&homeserver($docuname,$docudom);
                   2758:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2759: }
                   2760: 
1.531     albertel 2761: sub renameuserfile {
                   2762:     my ($docuname,$docudom,$old,$new)=@_;
                   2763:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2764:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2765:                         &escape("$old").':'.&escape("$new"),$home);
                   2766:     if ($result eq 'ok') {
                   2767:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2768:             my $oldmeta = $old.'.meta';
                   2769:             my $newmeta = $new.'.meta';
                   2770:             my $metaresult = 
                   2771:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2772: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2773:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2774:             my $sqlresult = 
1.823     albertel 2775:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2776:                                         'portfolio_metadata',$group,
                   2777:                                         'delete');
1.798     raeburn  2778:         }
                   2779:     }
                   2780:     return $result;
1.531     albertel 2781: }
                   2782: 
1.14      www      2783: # ------------------------------------------------------------------------- Log
                   2784: 
                   2785: sub log {
                   2786:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2787:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2788: }
                   2789: 
                   2790: # ------------------------------------------------------------------ Course Log
1.352     www      2791: #
                   2792: # This routine flushes several buffers of non-mission-critical nature
                   2793: #
1.157     www      2794: 
                   2795: sub flushcourselogs {
1.352     www      2796:     &logthis('Flushing log buffers');
                   2797: #
                   2798: # course logs
                   2799: # This is a log of all transactions in a course, which can be used
                   2800: # for data mining purposes
                   2801: #
                   2802: # It also collects the courseid database, which lists last transaction
                   2803: # times and course titles for all courseids
                   2804: #
                   2805:     my %courseidbuffer=();
1.921     raeburn  2806:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2807:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2808: 		          &escape($courselogs{$crsid}),
                   2809: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2810: 	    delete $courselogs{$crsid};
                   2811:         } else {
                   2812:             &logthis('Failed to flush log buffer for '.$crsid);
                   2813:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2814:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2815:                         " exceeded maximum size, deleting.</font>");
                   2816:                delete $courselogs{$crsid};
                   2817:             }
1.352     www      2818:         }
1.920     raeburn  2819:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2820:             'description' => $coursedescrbuf{$crsid},
                   2821:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2822:             'type'        => $coursetypebuf{$crsid},
                   2823:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2824:         };
1.191     harris41 2825:     }
1.352     www      2826: #
                   2827: # Write course id database (reverse lookup) to homeserver of courses 
                   2828: # Is used in pickcourse
                   2829: #
1.840     albertel 2830:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2831:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2832:                                     $courseidbuffer{$crs_home},
                   2833:                                     $crs_home,'timeonly');
1.352     www      2834:     }
                   2835: #
                   2836: # File accesses
                   2837: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2838: #
1.449     matthew  2839:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2840:         if ($entry =~ /___count$/) {
                   2841:             my ($dom,$name);
1.807     albertel 2842:             ($dom,$name,undef)=
1.811     albertel 2843: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2844:             if (! defined($dom) || $dom eq '' || 
                   2845:                 ! defined($name) || $name eq '') {
1.620     albertel 2846:                 my $cid = $env{'request.course.id'};
                   2847:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2848:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2849:             }
1.450     matthew  2850:             my $value = $accesshash{$entry};
                   2851:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2852:             my %temphash=($url => $value);
1.449     matthew  2853:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2854:             if ($result eq 'ok') {
                   2855:                 delete $accesshash{$entry};
                   2856:             } elsif ($result eq 'unknown_cmd') {
                   2857:                 # Target server has old code running on it.
1.450     matthew  2858:                 my %temphash=($entry => $value);
1.449     matthew  2859:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2860:                     delete $accesshash{$entry};
                   2861:                 }
                   2862:             }
                   2863:         } else {
1.811     albertel 2864:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2865:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2866:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2867:                 delete $accesshash{$entry};
                   2868:             }
1.185     www      2869:         }
1.191     harris41 2870:     }
1.352     www      2871: #
                   2872: # Roles
                   2873: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2874: #
1.800     albertel 2875:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2876:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2877: 	    split(/\:/,$entry);
                   2878:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2879:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2880:                 $rudom,$runame) eq 'ok') {
                   2881: 	    delete $userrolehash{$entry};
                   2882:         }
                   2883:     }
1.662     raeburn  2884: #
                   2885: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2886: #
                   2887:     my %domrolebuffer = ();
1.1000    raeburn  2888:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2889:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2890:         if ($domrolebuffer{$rudom}) {
                   2891:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2892:                       '='.&escape($domainrolehash{$entry});
                   2893:         } else {
                   2894:             $domrolebuffer{$rudom}.=&escape($entry).
                   2895:                       '='.&escape($domainrolehash{$entry});
                   2896:         }
                   2897:         delete $domainrolehash{$entry};
                   2898:     }
                   2899:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2900: 	my %servers = &get_servers($dom,'library');
                   2901: 	foreach my $tryserver (keys(%servers)) {
                   2902: 	    unless (&reply('domroleput:'.$dom.':'.
                   2903: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2904: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2905: 	    }
1.662     raeburn  2906:         }
                   2907:     }
1.186     www      2908:     $dumpcount++;
1.157     www      2909: }
                   2910: 
                   2911: sub courselog {
                   2912:     my $what=shift;
1.158     www      2913:     $what=time.':'.$what;
1.620     albertel 2914:     unless ($env{'request.course.id'}) { return ''; }
                   2915:     $coursedombuf{$env{'request.course.id'}}=
                   2916:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2917:     $coursenumbuf{$env{'request.course.id'}}=
                   2918:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2919:     $coursehombuf{$env{'request.course.id'}}=
                   2920:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2921:     $coursedescrbuf{$env{'request.course.id'}}=
                   2922:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2923:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2924:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2925:     $courseownerbuf{$env{'request.course.id'}}=
                   2926:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2927:     $coursetypebuf{$env{'request.course.id'}}=
                   2928:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2929:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2930: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2931:     } else {
1.620     albertel 2932: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2933:     }
1.620     albertel 2934:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2935: 	&flushcourselogs();
                   2936:     }
1.158     www      2937: }
                   2938: 
                   2939: sub courseacclog {
                   2940:     my $fnsymb=shift;
1.620     albertel 2941:     unless ($env{'request.course.id'}) { return ''; }
                   2942:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2943:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2944:         $what.=':POST';
1.583     matthew  2945:         # FIXME: Probably ought to escape things....
1.800     albertel 2946: 	foreach my $key (keys(%env)) {
                   2947:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2948:                 my $formitem = $1;
                   2949:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2950:                     $what.=':'.$formitem.'='.$env{$key};
                   2951:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2952:                     $what.=':'.$formitem.'='.$env{$key};
                   2953:                 }
1.158     www      2954:             }
1.191     harris41 2955:         }
1.583     matthew  2956:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2957:         # FIXME: We should not be depending on a form parameter that someone
                   2958:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2959:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2960:             $what.= ':POST';
                   2961:             # FIXME: Probably ought to escape things....
                   2962:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2963:                                  'crsdiscuss') {
1.620     albertel 2964:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2965:             }
                   2966:         }
1.158     www      2967:     }
                   2968:     &courselog($what);
1.149     www      2969: }
                   2970: 
1.185     www      2971: sub countacc {
                   2972:     my $url=&declutter(shift);
1.458     matthew  2973:     return if (! defined($url) || $url eq '');
1.620     albertel 2974:     unless ($env{'request.course.id'}) { return ''; }
                   2975:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2976:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2977:     $accesshash{$key}++;
1.185     www      2978: }
1.349     www      2979: 
1.361     www      2980: sub linklog {
                   2981:     my ($from,$to)=@_;
                   2982:     $from=&declutter($from);
                   2983:     $to=&declutter($to);
                   2984:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2985:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2986: }
                   2987:   
1.349     www      2988: sub userrolelog {
                   2989:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2990:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2991:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2992:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2993:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2994:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2995:        $userrolehash
                   2996:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2997:                     =$tend.':'.$tstart;
1.662     raeburn  2998:     }
1.898     albertel 2999:     if (($env{'request.role'} =~ /dc\./) &&
                   3000: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3001: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3002: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3003:          ($trole=~/^co/))) {
1.898     albertel 3004:        $userrolehash
                   3005:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3006:                     =$tend.':'.$tstart;
                   3007:     }
1.662     raeburn  3008:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3009:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3010:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3011:         ($trole=~/^sc/)) {
                   3012:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3013:        $domainrolehash
                   3014:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3015:                     = $tend.':'.$tstart;
                   3016:     }
1.351     www      3017: }
                   3018: 
1.957     raeburn  3019: sub courserolelog {
                   3020:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3021:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3022:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3023:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3024:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3025:         ($trole eq 'co')) {
1.957     raeburn  3026:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3027:             my $cdom = $1;
                   3028:             my $cnum = $2;
                   3029:             my $sec = $3;
                   3030:             my $namespace = 'rolelog';
                   3031:             my %storehash = (
                   3032:                                role    => $trole,
                   3033:                                start   => $tstart,
                   3034:                                end     => $tend,
                   3035:                                selfenroll => $selfenroll,
                   3036:                                context    => $context,
                   3037:                             );
                   3038:             if ($trole eq 'gr') {
                   3039:                 $namespace = 'groupslog';
                   3040:                 $storehash{'group'} = $sec;
                   3041:             } else {
                   3042:                 $storehash{'section'} = $sec;
                   3043:             }
                   3044:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3045:             if (($trole ne 'st') || ($sec ne '')) {
                   3046:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3047:             }
1.957     raeburn  3048:         }
                   3049:     }
                   3050:     return;
                   3051: }
                   3052: 
1.351     www      3053: sub get_course_adv_roles {
1.948     raeburn  3054:     my ($cid,$codes) = @_;
1.620     albertel 3055:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3056:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3057:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3058:     my %nothide=();
1.800     albertel 3059:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3060:         if ($user !~ /:/) {
                   3061: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3062:         } else {
                   3063:             $nothide{$user}=1;
                   3064:         }
1.470     www      3065:     }
1.351     www      3066:     my %returnhash=();
                   3067:     my %dumphash=
                   3068:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3069:     my $now=time;
1.997     raeburn  3070:     my %privileged;
1.1000    raeburn  3071:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3072: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3073:         if (($tstart) && ($tstart<0)) { next; }
                   3074:         if (($tend) && ($tend<$now)) { next; }
                   3075:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3076:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3077: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3078:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3079:             my %dompersonnel =
1.998     raeburn  3080:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3081:             $privileged{$domain} = {};
                   3082:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3083:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3084:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3085:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3086:                         $privileged{$udom}{$uname} = 1;
                   3087:                     }
                   3088:                 }
                   3089:             }
                   3090:         }
                   3091:         if ((exists($privileged{$domain}{$username})) && 
                   3092:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3093: 	if ($role eq 'cr') { next; }
1.948     raeburn  3094:         if ($codes) {
                   3095:             if ($section) { $role .= ':'.$section; }
                   3096:             if ($returnhash{$role}) {
                   3097:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3098:             } else {
                   3099:                 $returnhash{$role}=$username.':'.$domain;
                   3100:             }
1.351     www      3101:         } else {
1.988     raeburn  3102:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3103:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3104:             if ($returnhash{$key}) {
                   3105: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3106:             } else {
                   3107:                 $returnhash{$key}=$username.':'.$domain;
                   3108:             }
1.351     www      3109:         }
1.948     raeburn  3110:     }
1.400     www      3111:     return %returnhash;
                   3112: }
                   3113: 
                   3114: sub get_my_roles {
1.937     raeburn  3115:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3116:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3117:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3118:     my (%dumphash,%nothide);
1.858     raeburn  3119:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3120:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3121:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3122:     } else {
                   3123:         %dumphash=
1.400     www      3124:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3125:         if ($hidepriv) {
                   3126:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3127:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3128:                 if ($user !~ /:/) {
                   3129:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3130:                 } else {
                   3131:                     $nothide{$user} = 1;
                   3132:                 }
                   3133:             }
                   3134:         }
1.858     raeburn  3135:     }
1.400     www      3136:     my %returnhash=();
                   3137:     my $now=time;
1.999     raeburn  3138:     my %privileged;
1.800     albertel 3139:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3140:         my ($role,$tend,$tstart);
                   3141:         if ($context eq 'userroles') {
                   3142: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3143:         } else {
                   3144:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3145:         }
1.400     www      3146:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3147:         my $status = 'active';
1.939     raeburn  3148:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3149:             $status = 'previous';
                   3150:         } 
                   3151:         if (($tstart) && ($now<$tstart)) {
                   3152:             $status = 'future';
                   3153:         }
                   3154:         if (ref($types) eq 'ARRAY') {
                   3155:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3156:                 next;
                   3157:             } 
                   3158:         } else {
                   3159:             if ($status ne 'active') {
                   3160:                 next;
                   3161:             }
                   3162:         }
1.867     raeburn  3163:         my ($rolecode,$username,$domain,$section,$area);
                   3164:         if ($context eq 'userroles') {
                   3165:             ($area,$rolecode) = split(/_/,$entry);
                   3166:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3167:         } else {
                   3168:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3169:         }
1.832     raeburn  3170:         if (ref($roledoms) eq 'ARRAY') {
                   3171:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3172:                 next;
                   3173:             }
                   3174:         }
                   3175:         if (ref($roles) eq 'ARRAY') {
                   3176:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3177:                 if ($role =~ /^cr\//) {
                   3178:                     if (!grep(/^cr$/,@{$roles})) {
                   3179:                         next;
                   3180:                     }
                   3181:                 } else {
                   3182:                     next;
                   3183:                 }
1.832     raeburn  3184:             }
1.867     raeburn  3185:         }
1.937     raeburn  3186:         if ($hidepriv) {
1.999     raeburn  3187:             if ($context eq 'userroles') {
                   3188:                 if ((&privileged($username,$domain)) &&
                   3189:                     (!$nothide{$username.':'.$domain})) {
                   3190:                     next;
                   3191:                 }
                   3192:             } else {
                   3193:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3194:                     my %dompersonnel =
                   3195:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3196:                     $privileged{$domain} = {};
                   3197:                     if (keys(%dompersonnel)) {
                   3198:                         foreach my $server (keys(%dompersonnel)) {
                   3199:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3200:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3201:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3202:                                     $privileged{$udom}{$uname} = $trole;
                   3203:                                 }
                   3204:                             }
                   3205:                         }
                   3206:                     }
                   3207:                 }
                   3208:                 if (exists($privileged{$domain}{$username})) {
                   3209:                     if (!$nothide{$username.':'.$domain}) {
                   3210:                         next;
                   3211:                     }
                   3212:                 }
1.937     raeburn  3213:             }
                   3214:         }
1.933     raeburn  3215:         if ($withsec) {
                   3216:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3217:                 $tstart.':'.$tend;
                   3218:         } else {
                   3219:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3220:         }
1.832     raeburn  3221:     }
1.373     www      3222:     return %returnhash;
1.399     www      3223: }
                   3224: 
                   3225: # ----------------------------------------------------- Frontpage Announcements
                   3226: #
                   3227: #
                   3228: 
                   3229: sub postannounce {
                   3230:     my ($server,$text)=@_;
1.844     albertel 3231:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3232:     unless ($text=~/\w/) { $text=''; }
                   3233:     return &reply('setannounce:'.&escape($text),$server);
                   3234: }
                   3235: 
                   3236: sub getannounce {
1.448     albertel 3237: 
                   3238:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3239: 	my $announcement='';
1.800     albertel 3240: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3241: 	close($fh);
1.399     www      3242: 	if ($announcement=~/\w/) { 
                   3243: 	    return 
                   3244:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3245:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3246: 	} else {
                   3247: 	    return '';
                   3248: 	}
                   3249:     } else {
                   3250: 	return '';
                   3251:     }
1.351     www      3252: }
1.353     www      3253: 
                   3254: # ---------------------------------------------------------- Course ID routines
                   3255: # Deal with domain's nohist_courseid.db files
                   3256: #
                   3257: 
                   3258: sub courseidput {
1.921     raeburn  3259:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3260:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3261:     my $outcome;
                   3262:     if ($caller eq 'timeonly') {
                   3263:         my $cids = '';
                   3264:         foreach my $item (keys(%$storehash)) {
                   3265:             $cids.=&escape($item).'&';
                   3266:         }
                   3267:         $cids=~s/\&$//;
                   3268:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3269:                           $coursehome);       
                   3270:     } else {
                   3271:         my $items = '';
                   3272:         foreach my $item (keys(%$storehash)) {
                   3273:             $items.= &escape($item).'='.
                   3274:                      &freeze_escape($$storehash{$item}).'&';
                   3275:         }
                   3276:         $items=~s/\&$//;
                   3277:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3278:                           $coursehome);
1.918     raeburn  3279:     }
                   3280:     if ($outcome eq 'unknown_cmd') {
                   3281:         my $what;
                   3282:         foreach my $cid (keys(%$storehash)) {
                   3283:             $what .= &escape($cid).'=';
1.921     raeburn  3284:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3285:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3286:             }
                   3287:             $what =~ s/\:$/&/;
                   3288:         }
                   3289:         $what =~ s/\&$//;  
                   3290:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3291:     } else {
                   3292:         return $outcome;
                   3293:     }
1.353     www      3294: }
                   3295: 
                   3296: sub courseiddump {
1.921     raeburn  3297:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3298:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3299:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3300:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3301:     my $as_hash = 1;
                   3302:     my %returnhash;
                   3303:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3304:     my %libserv = &all_library();
                   3305:     foreach my $tryserver (keys(%libserv)) {
                   3306:         if ( (  $hostidflag == 1 
                   3307: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3308: 	     || (!defined($hostidflag)) ) {
                   3309: 
1.918     raeburn  3310: 	    if (($domfilter eq '') ||
                   3311: 		(&host_domain($tryserver) eq $domfilter)) {
                   3312:                 my $rep = 
                   3313:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3314:                          $sincefilter.':'.&escape($descfilter).':'.
                   3315:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3316:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3317:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3318:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3319:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3320:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3321:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3322:                          &escape($creationcontext).':'.$domcloner,
                   3323:                          $tryserver);
1.918     raeburn  3324:                 my @pairs=split(/\&/,$rep);
                   3325:                 foreach my $item (@pairs) {
                   3326:                     my ($key,$value)=split(/\=/,$item,2);
                   3327:                     $key = &unescape($key);
                   3328:                     next if ($key =~ /^error: 2 /);
                   3329:                     my $result = &thaw_unescape($value);
                   3330:                     if (ref($result) eq 'HASH') {
                   3331:                         $returnhash{$key}=$result;
                   3332:                     } else {
1.921     raeburn  3333:                         my @responses = split(/:/,$value);
                   3334:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3335:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3336:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3337:                         }
1.1008    raeburn  3338:                     }
1.353     www      3339:                 }
                   3340:             }
                   3341:         }
                   3342:     }
                   3343:     return %returnhash;
                   3344: }
                   3345: 
1.1055    raeburn  3346: sub courselastaccess {
                   3347:     my ($cdom,$cnum,$hostidref) = @_;
                   3348:     my %returnhash;
                   3349:     if ($cdom && $cnum) {
                   3350:         my $chome = &homeserver($cnum,$cdom);
                   3351:         if ($chome ne 'no_host') {
                   3352:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3353:             &extract_lastaccess(\%returnhash,$rep);
                   3354:         }
                   3355:     } else {
                   3356:         if (!$cdom) { $cdom=''; }
                   3357:         my %libserv = &all_library();
                   3358:         foreach my $tryserver (keys(%libserv)) {
                   3359:             if (ref($hostidref) eq 'ARRAY') {
                   3360:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3361:             } 
                   3362:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3363:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3364:                 &extract_lastaccess(\%returnhash,$rep);
                   3365:             }
                   3366:         }
                   3367:     }
                   3368:     return %returnhash;
                   3369: }
                   3370: 
                   3371: sub extract_lastaccess {
                   3372:     my ($returnhash,$rep) = @_;
                   3373:     if (ref($returnhash) eq 'HASH') {
                   3374:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3375:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3376:                  $rep eq '') {
                   3377:             my @pairs=split(/\&/,$rep);
                   3378:             foreach my $item (@pairs) {
                   3379:                 my ($key,$value)=split(/\=/,$item,2);
                   3380:                 $key = &unescape($key);
                   3381:                 next if ($key =~ /^error: 2 /);
                   3382:                 $returnhash->{$key} = &thaw_unescape($value);
                   3383:             }
                   3384:         }
                   3385:     }
                   3386:     return;
                   3387: }
                   3388: 
1.658     raeburn  3389: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3390: 
                   3391: sub dcmailput {
1.685     raeburn  3392:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3393:     my $status = &Apache::lonnet::critical(
1.740     www      3394:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3395:        &escape($message),$server);
1.662     raeburn  3396:     return $status;
                   3397: }
                   3398: 
1.658     raeburn  3399: sub dcmaildump {
                   3400:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3401:     my %returnhash=();
1.846     albertel 3402: 
                   3403:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3404:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3405:                                                          &escape($enddate).':';
                   3406: 	my @esc_senders=map { &escape($_)} @$senders;
                   3407: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3408: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3409:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3410:             if (($key) && ($value)) {
                   3411:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3412:             }
                   3413:         }
                   3414:     }
                   3415:     return %returnhash;
                   3416: }
1.662     raeburn  3417: # ---------------------------------------------------------- Domain roles
                   3418: 
                   3419: sub get_domain_roles {
                   3420:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3421:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3422:         $startdate = '.';
                   3423:     }
1.1018    raeburn  3424:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3425:         $enddate = '.';
                   3426:     }
1.922     raeburn  3427:     my $rolelist;
                   3428:     if (ref($roles) eq 'ARRAY') {
                   3429:         $rolelist = join(':',@{$roles});
                   3430:     }
1.662     raeburn  3431:     my %personnel = ();
1.841     albertel 3432: 
                   3433:     my %servers = &get_servers($dom,'library');
                   3434:     foreach my $tryserver (keys(%servers)) {
                   3435: 	%{$personnel{$tryserver}}=();
                   3436: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3437: 					    &escape($startdate).':'.
                   3438: 					    &escape($enddate).':'.
                   3439: 					    &escape($rolelist), $tryserver))) {
                   3440: 	    my ($key,$value) = split(/\=/,$line,2);
                   3441: 	    if (($key) && ($value)) {
                   3442: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3443: 	    }
                   3444: 	}
1.662     raeburn  3445:     }
                   3446:     return %personnel;
                   3447: }
1.658     raeburn  3448: 
1.149     www      3449: # ----------------------------------------------------------- Check out an item
                   3450: 
1.504     albertel 3451: sub get_first_access {
                   3452:     my ($type,$argsymb)=@_;
1.790     albertel 3453:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3454:     if ($argsymb) { $symb=$argsymb; }
                   3455:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3456:     if ($type eq 'course') {
                   3457: 	$res='course';
                   3458:     } elsif ($type eq 'map') {
1.588     albertel 3459: 	$res=&symbread($map);
                   3460:     } else {
                   3461: 	$res=$symb;
                   3462:     }
                   3463:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3464:     return $times{"$courseid\0$res"};
1.504     albertel 3465: }
                   3466: 
                   3467: sub set_first_access {
                   3468:     my ($type)=@_;
1.790     albertel 3469:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3470:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3471:     if ($type eq 'course') {
                   3472: 	$res='course';
                   3473:     } elsif ($type eq 'map') {
1.588     albertel 3474: 	$res=&symbread($map);
                   3475:     } else {
                   3476: 	$res=$symb;
                   3477:     }
                   3478:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3479:     if (!$firstaccess) {
1.588     albertel 3480: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3481:     }
                   3482:     return 'already_set';
1.504     albertel 3483: }
                   3484: 
1.149     www      3485: sub checkout {
                   3486:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3487:     my $now=time;
                   3488:     my $lonhost=$perlvar{'lonHostID'};
                   3489:     my $infostr=&escape(
1.234     www      3490:                  'CHECKOUTTOKEN&'.
1.149     www      3491:                  $tuname.'&'.
                   3492:                  $tudom.'&'.
                   3493:                  $tcrsid.'&'.
                   3494:                  $symb.'&'.
                   3495: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3496:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3497:     if ($token=~/^error\:/) { 
1.672     albertel 3498:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3499:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3500:                  "</font>");
                   3501:         return ''; 
                   3502:     }
                   3503: 
1.149     www      3504:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3505:     $token=~tr/a-z/A-Z/;
                   3506: 
1.153     www      3507:     my %infohash=('resource.0.outtoken' => $token,
                   3508:                   'resource.0.checkouttime' => $now,
                   3509:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3510: 
                   3511:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3512:        return '';
1.151     www      3513:     } else {
1.672     albertel 3514:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3515:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3516:                  "</font>");
1.149     www      3517:     }    
                   3518: 
                   3519:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3520:                          &escape('Checkout '.$infostr.' - '.
                   3521:                                                  $token)) ne 'ok') {
                   3522: 	return '';
1.151     www      3523:     } else {
1.672     albertel 3524:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3525:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3526:                  "</font>");
1.149     www      3527:     }
1.151     www      3528:     return $token;
1.149     www      3529: }
                   3530: 
                   3531: # ------------------------------------------------------------ Check in an item
                   3532: 
                   3533: sub checkin {
                   3534:     my $token=shift;
1.150     www      3535:     my $now=time;
                   3536:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3537:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3538:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3539:     $dtoken=~s/\W/\_/g;
1.234     www      3540:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3541:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3542: 
1.154     www      3543:     unless (($tuname) && ($tudom)) {
                   3544:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3545:         return '';
                   3546:     }
                   3547:     
                   3548:     unless (&allowed('mgr',$tcrsid)) {
                   3549:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3550:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3551:         return '';
                   3552:     }
                   3553: 
1.153     www      3554:     my %infohash=('resource.0.intoken' => $token,
                   3555:                   'resource.0.checkintime' => $now,
                   3556:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3557: 
                   3558:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3559:        return '';
                   3560:     }    
                   3561: 
                   3562:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3563:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3564: 	return '';
                   3565:     }
                   3566: 
                   3567:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3568: }
                   3569: 
                   3570: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3571: 
                   3572: sub expirespread {
                   3573:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3574:     my $cid=$env{'request.course.id'}; 
1.110     www      3575:     if ($cid) {
                   3576:        my $now=time;
                   3577:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3578:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3579:                             $env{'course.'.$cid.'.num'}.
1.110     www      3580: 	        	    ':nohist_expirationdates:'.
                   3581:                             &escape($key).'='.$now,
1.620     albertel 3582:                             $env{'course.'.$cid.'.home'})
1.110     www      3583:     }
                   3584:     return 'ok';
1.14      www      3585: }
                   3586: 
1.109     www      3587: # ----------------------------------------------------- Devalidate Spreadsheets
                   3588: 
                   3589: sub devalidate {
1.325     www      3590:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3591:     my $cid=$env{'request.course.id'}; 
1.109     www      3592:     if ($cid) {
1.391     matthew  3593:         # delete the stored spreadsheets for
                   3594:         # - the student level sheet of this user in course's homespace
                   3595:         # - the assessment level sheet for this resource 
                   3596:         #   for this user in user's homespace
1.553     albertel 3597: 	# - current conditional state info
1.325     www      3598: 	my $key=$uname.':'.$udom.':';
1.109     www      3599:         my $status=
1.299     matthew  3600: 	    &del('nohist_calculatedsheets',
1.391     matthew  3601: 		 [$key.'studentcalc:'],
1.620     albertel 3602: 		 $env{'course.'.$cid.'.domain'},
                   3603: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3604: 		.' '.
                   3605: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3606: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3607:         unless ($status eq 'ok ok') {
                   3608:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3609:                     $uname.' at '.$udom.' for '.
1.109     www      3610: 		    $symb.': '.$status);
1.133     albertel 3611:         }
1.553     albertel 3612: 	&delenv('user.state.'.$cid);
1.109     www      3613:     }
                   3614: }
                   3615: 
1.265     albertel 3616: sub get_scalar {
                   3617:     my ($string,$end) = @_;
                   3618:     my $value;
                   3619:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3620: 	$value = $1;
                   3621:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3622: 	$value = $1;
                   3623:     }
                   3624:     return &unescape($value);
                   3625: }
                   3626: 
                   3627: sub array2str {
                   3628:   my (@array) = @_;
                   3629:   my $result=&arrayref2str(\@array);
                   3630:   $result=~s/^__ARRAY_REF__//;
                   3631:   $result=~s/__END_ARRAY_REF__$//;
                   3632:   return $result;
                   3633: }
                   3634: 
1.204     albertel 3635: sub arrayref2str {
                   3636:   my ($arrayref) = @_;
1.265     albertel 3637:   my $result='__ARRAY_REF__';
1.204     albertel 3638:   foreach my $elem (@$arrayref) {
1.265     albertel 3639:     if(ref($elem) eq 'ARRAY') {
                   3640:       $result.=&arrayref2str($elem).'&';
                   3641:     } elsif(ref($elem) eq 'HASH') {
                   3642:       $result.=&hashref2str($elem).'&';
                   3643:     } elsif(ref($elem)) {
                   3644:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3645:     } else {
                   3646:       $result.=&escape($elem).'&';
                   3647:     }
                   3648:   }
                   3649:   $result=~s/\&$//;
1.265     albertel 3650:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3651:   return $result;
                   3652: }
                   3653: 
1.168     albertel 3654: sub hash2str {
1.204     albertel 3655:   my (%hash) = @_;
                   3656:   my $result=&hashref2str(\%hash);
1.265     albertel 3657:   $result=~s/^__HASH_REF__//;
                   3658:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3659:   return $result;
                   3660: }
                   3661: 
                   3662: sub hashref2str {
                   3663:   my ($hashref)=@_;
1.265     albertel 3664:   my $result='__HASH_REF__';
1.800     albertel 3665:   foreach my $key (sort(keys(%$hashref))) {
                   3666:     if (ref($key) eq 'ARRAY') {
                   3667:       $result.=&arrayref2str($key).'=';
                   3668:     } elsif (ref($key) eq 'HASH') {
                   3669:       $result.=&hashref2str($key).'=';
                   3670:     } elsif (ref($key)) {
1.265     albertel 3671:       $result.='=';
1.800     albertel 3672:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3673:     } else {
1.800     albertel 3674: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3675:     }
                   3676: 
1.800     albertel 3677:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3678:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3679:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3680:       $result.=&hashref2str($hashref->{$key}).'&';
                   3681:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3682:        $result.='&';
1.800     albertel 3683:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3684:     } else {
1.800     albertel 3685:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3686:     }
                   3687:   }
1.168     albertel 3688:   $result=~s/\&$//;
1.265     albertel 3689:   $result .= '__END_HASH_REF__';
1.168     albertel 3690:   return $result;
                   3691: }
                   3692: 
                   3693: sub str2hash {
1.265     albertel 3694:     my ($string)=@_;
                   3695:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3696:     return %$hash;
                   3697: }
                   3698: 
                   3699: sub str2hashref {
1.168     albertel 3700:   my ($string) = @_;
1.265     albertel 3701: 
                   3702:   my %hash;
                   3703: 
                   3704:   if($string !~ /^__HASH_REF__/) {
                   3705:       if (! ($string eq '' || !defined($string))) {
                   3706: 	  $hash{'error'}='Not hash reference';
                   3707:       }
                   3708:       return (\%hash, $string);
                   3709:   }
                   3710: 
                   3711:   $string =~ s/^__HASH_REF__//;
                   3712: 
                   3713:   while($string !~ /^__END_HASH_REF__/) {
                   3714:       #key
                   3715:       my $key='';
                   3716:       if($string =~ /^__HASH_REF__/) {
                   3717:           ($key, $string)=&str2hashref($string);
                   3718:           if(defined($key->{'error'})) {
                   3719:               $hash{'error'}='Bad data';
                   3720:               return (\%hash, $string);
                   3721:           }
                   3722:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3723:           ($key, $string)=&str2arrayref($string);
                   3724:           if($key->[0] eq 'Array reference error') {
                   3725:               $hash{'error'}='Bad data';
                   3726:               return (\%hash, $string);
                   3727:           }
                   3728:       } else {
                   3729:           $string =~ s/^(.*?)=//;
1.267     albertel 3730: 	  $key=&unescape($1);
1.265     albertel 3731:       }
                   3732:       $string =~ s/^=//;
                   3733: 
                   3734:       #value
                   3735:       my $value='';
                   3736:       if($string =~ /^__HASH_REF__/) {
                   3737:           ($value, $string)=&str2hashref($string);
                   3738:           if(defined($value->{'error'})) {
                   3739:               $hash{'error'}='Bad data';
                   3740:               return (\%hash, $string);
                   3741:           }
                   3742:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3743:           ($value, $string)=&str2arrayref($string);
                   3744:           if($value->[0] eq 'Array reference error') {
                   3745:               $hash{'error'}='Bad data';
                   3746:               return (\%hash, $string);
                   3747:           }
                   3748:       } else {
                   3749: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3750:       }
                   3751:       $string =~ s/^&//;
                   3752: 
                   3753:       $hash{$key}=$value;
1.204     albertel 3754:   }
1.265     albertel 3755: 
                   3756:   $string =~ s/^__END_HASH_REF__//;
                   3757: 
                   3758:   return (\%hash, $string);
1.204     albertel 3759: }
                   3760: 
                   3761: sub str2array {
1.265     albertel 3762:     my ($string)=@_;
                   3763:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3764:     return @$array;
                   3765: }
                   3766: 
                   3767: sub str2arrayref {
1.204     albertel 3768:   my ($string) = @_;
1.265     albertel 3769:   my @array;
                   3770: 
                   3771:   if($string !~ /^__ARRAY_REF__/) {
                   3772:       if (! ($string eq '' || !defined($string))) {
                   3773: 	  $array[0]='Array reference error';
                   3774:       }
                   3775:       return (\@array, $string);
                   3776:   }
                   3777: 
                   3778:   $string =~ s/^__ARRAY_REF__//;
                   3779: 
                   3780:   while($string !~ /^__END_ARRAY_REF__/) {
                   3781:       my $value='';
                   3782:       if($string =~ /^__HASH_REF__/) {
                   3783:           ($value, $string)=&str2hashref($string);
                   3784:           if(defined($value->{'error'})) {
                   3785:               $array[0] ='Array reference error';
                   3786:               return (\@array, $string);
                   3787:           }
                   3788:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3789:           ($value, $string)=&str2arrayref($string);
                   3790:           if($value->[0] eq 'Array reference error') {
                   3791:               $array[0] ='Array reference error';
                   3792:               return (\@array, $string);
                   3793:           }
                   3794:       } else {
                   3795: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3796:       }
                   3797:       $string =~ s/^&//;
                   3798: 
                   3799:       push(@array, $value);
1.191     harris41 3800:   }
1.265     albertel 3801: 
                   3802:   $string =~ s/^__END_ARRAY_REF__//;
                   3803: 
                   3804:   return (\@array, $string);
1.168     albertel 3805: }
                   3806: 
1.167     albertel 3807: # -------------------------------------------------------------------Temp Store
                   3808: 
1.168     albertel 3809: sub tmpreset {
                   3810:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3811:   if (!$symb) {
                   3812:     $symb=&symbread();
1.620     albertel 3813:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3814:   }
                   3815:   $symb=escape($symb);
                   3816: 
1.620     albertel 3817:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3818:   $namespace=~s/\//\_/g;
                   3819:   $namespace=~s/\W//g;
                   3820: 
1.620     albertel 3821:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3822:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3823:   if ($domain eq 'public' && $stuname eq 'public') {
                   3824:       $stuname=$ENV{'REMOTE_ADDR'};
                   3825:   }
1.168     albertel 3826:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3827:   my %hash;
                   3828:   if (tie(%hash,'GDBM_File',
                   3829: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3830: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3831:     foreach my $key (keys(%hash)) {
1.180     albertel 3832:       if ($key=~ /:$symb/) {
1.168     albertel 3833: 	delete($hash{$key});
                   3834:       }
                   3835:     }
                   3836:   }
                   3837: }
                   3838: 
1.167     albertel 3839: sub tmpstore {
1.168     albertel 3840:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3841: 
                   3842:   if (!$symb) {
                   3843:     $symb=&symbread();
1.620     albertel 3844:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3845:   }
                   3846:   $symb=escape($symb);
                   3847: 
                   3848:   if (!$namespace) {
                   3849:     # I don't think we would ever want to store this for a course.
                   3850:     # it seems this will only be used if we don't have a course.
1.620     albertel 3851:     #$namespace=$env{'request.course.id'};
1.168     albertel 3852:     #if (!$namespace) {
1.620     albertel 3853:       $namespace=$env{'request.state'};
1.168     albertel 3854:     #}
                   3855:   }
                   3856:   $namespace=~s/\//\_/g;
                   3857:   $namespace=~s/\W//g;
1.620     albertel 3858:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3859:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3860:   if ($domain eq 'public' && $stuname eq 'public') {
                   3861:       $stuname=$ENV{'REMOTE_ADDR'};
                   3862:   }
1.168     albertel 3863:   my $now=time;
                   3864:   my %hash;
                   3865:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3866:   if (tie(%hash,'GDBM_File',
                   3867: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3868: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3869:     $hash{"version:$symb"}++;
                   3870:     my $version=$hash{"version:$symb"};
                   3871:     my $allkeys=''; 
                   3872:     foreach my $key (keys(%$storehash)) {
                   3873:       $allkeys.=$key.':';
1.591     albertel 3874:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3875:     }
                   3876:     $hash{"$version:$symb:timestamp"}=$now;
                   3877:     $allkeys.='timestamp';
                   3878:     $hash{"$version:keys:$symb"}=$allkeys;
                   3879:     if (untie(%hash)) {
                   3880:       return 'ok';
                   3881:     } else {
                   3882:       return "error:$!";
                   3883:     }
                   3884:   } else {
                   3885:     return "error:$!";
                   3886:   }
                   3887: }
1.167     albertel 3888: 
1.168     albertel 3889: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3890: 
1.168     albertel 3891: sub tmprestore {
                   3892:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3893: 
1.168     albertel 3894:   if (!$symb) {
                   3895:     $symb=&symbread();
1.620     albertel 3896:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3897:   }
                   3898:   $symb=escape($symb);
                   3899: 
1.620     albertel 3900:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3901: 
1.620     albertel 3902:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3903:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3904:   if ($domain eq 'public' && $stuname eq 'public') {
                   3905:       $stuname=$ENV{'REMOTE_ADDR'};
                   3906:   }
1.168     albertel 3907:   my %returnhash;
                   3908:   $namespace=~s/\//\_/g;
                   3909:   $namespace=~s/\W//g;
                   3910:   my %hash;
                   3911:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3912:   if (tie(%hash,'GDBM_File',
                   3913: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3914: 	  &GDBM_READER(),0640)) {
1.168     albertel 3915:     my $version=$hash{"version:$symb"};
                   3916:     $returnhash{'version'}=$version;
                   3917:     my $scope;
                   3918:     for ($scope=1;$scope<=$version;$scope++) {
                   3919:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3920:       my @keys=split(/:/,$vkeys);
                   3921:       my $key;
                   3922:       $returnhash{"$scope:keys"}=$vkeys;
                   3923:       foreach $key (@keys) {
1.591     albertel 3924: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3925: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3926:       }
                   3927:     }
1.168     albertel 3928:     if (!(untie(%hash))) {
                   3929:       return "error:$!";
                   3930:     }
                   3931:   } else {
                   3932:     return "error:$!";
                   3933:   }
                   3934:   return %returnhash;
1.167     albertel 3935: }
                   3936: 
1.9       www      3937: # ----------------------------------------------------------------------- Store
                   3938: 
                   3939: sub store {
1.124     www      3940:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3941:     my $home='';
                   3942: 
1.168     albertel 3943:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3944: 
1.213     www      3945:     $symb=&symbclean($symb);
1.122     albertel 3946:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3947: 
1.620     albertel 3948:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3949:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3950: 
                   3951:     &devalidate($symb,$stuname,$domain);
1.109     www      3952: 
                   3953:     $symb=escape($symb);
1.187     www      3954:     if (!$namespace) { 
1.620     albertel 3955:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3956:           return ''; 
                   3957:        } 
                   3958:     }
1.620     albertel 3959:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3960: 
                   3961:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3962:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3963: 
1.12      www      3964:     my $namevalue='';
1.800     albertel 3965:     foreach my $key (keys(%$storehash)) {
                   3966:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3967:     }
1.12      www      3968:     $namevalue=~s/\&$//;
1.187     www      3969:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3970:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3971: }
                   3972: 
1.47      www      3973: # -------------------------------------------------------------- Critical Store
                   3974: 
                   3975: sub cstore {
1.124     www      3976:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3977:     my $home='';
                   3978: 
1.168     albertel 3979:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3980: 
1.213     www      3981:     $symb=&symbclean($symb);
1.122     albertel 3982:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3983: 
1.620     albertel 3984:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3985:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3986: 
                   3987:     &devalidate($symb,$stuname,$domain);
1.109     www      3988: 
                   3989:     $symb=escape($symb);
1.187     www      3990:     if (!$namespace) { 
1.620     albertel 3991:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3992:           return ''; 
                   3993:        } 
                   3994:     }
1.620     albertel 3995:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3996: 
                   3997:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3998:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3999: 
1.47      www      4000:     my $namevalue='';
1.800     albertel 4001:     foreach my $key (keys(%$storehash)) {
                   4002:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4003:     }
1.47      www      4004:     $namevalue=~s/\&$//;
1.187     www      4005:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4006:     return critical
                   4007:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4008: }
                   4009: 
1.9       www      4010: # --------------------------------------------------------------------- Restore
                   4011: 
                   4012: sub restore {
1.124     www      4013:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4014:     my $home='';
                   4015: 
1.168     albertel 4016:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4017: 
1.122     albertel 4018:     if (!$symb) {
                   4019:       unless ($symb=escape(&symbread())) { return ''; }
                   4020:     } else {
1.213     www      4021:       $symb=&escape(&symbclean($symb));
1.122     albertel 4022:     }
1.188     www      4023:     if (!$namespace) { 
1.620     albertel 4024:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4025:           return ''; 
                   4026:        } 
                   4027:     }
1.620     albertel 4028:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4029:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4030:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4031:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4032: 
1.12      www      4033:     my %returnhash=();
1.800     albertel 4034:     foreach my $line (split(/\&/,$answer)) {
                   4035: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4036:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4037:     }
1.75      www      4038:     my $version;
                   4039:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4040:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4041:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4042:        }
1.75      www      4043:     }
1.13      www      4044:     return %returnhash;
1.34      www      4045: }
                   4046: 
                   4047: # ---------------------------------------------------------- Course Description
                   4048: 
                   4049: sub coursedescription {
1.731     albertel 4050:     my ($courseid,$args)=@_;
1.34      www      4051:     $courseid=~s/^\///;
1.49      www      4052:     $courseid=~s/\_/\//g;
1.34      www      4053:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4054:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4055:     my $normalid=$cdomain.'_'.$cnum;
                   4056:     # need to always cache even if we get errors otherwise we keep 
                   4057:     # trying and trying and trying to get the course description.
                   4058:     my %envhash=();
                   4059:     my %returnhash=();
1.731     albertel 4060:     
                   4061:     my $expiretime=600;
                   4062:     if ($env{'request.course.id'} eq $normalid) {
                   4063: 	$expiretime=120;
                   4064:     }
                   4065: 
                   4066:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4067:     if (!$args->{'freshen_cache'}
                   4068: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4069: 	foreach my $key (keys(%env)) {
                   4070: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4071: 	    my ($setting) = $1;
                   4072: 	    $returnhash{$setting} = $env{$key};
                   4073: 	}
                   4074: 	return %returnhash;
                   4075:     }
                   4076: 
                   4077:     # get the data agin
                   4078:     if (!$args->{'one_time'}) {
                   4079: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4080:     }
1.811     albertel 4081: 
1.34      www      4082:     if ($chome ne 'no_host') {
1.302     albertel 4083:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4084:        if (!exists($returnhash{'con_lost'})) {
                   4085:            $returnhash{'home'}= $chome;
                   4086: 	   $returnhash{'domain'} = $cdomain;
                   4087: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4088:            if (!defined($returnhash{'type'})) {
                   4089:                $returnhash{'type'} = 'Course';
                   4090:            }
1.130     albertel 4091:            while (my ($name,$value) = each %returnhash) {
1.53      www      4092:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4093:            }
1.270     www      4094:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4095:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4096: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4097:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4098:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4099:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4100:        }
                   4101:     }
1.731     albertel 4102:     if (!$args->{'one_time'}) {
1.949     raeburn  4103: 	&appenv(\%envhash);
1.731     albertel 4104:     }
1.302     albertel 4105:     return %returnhash;
1.461     www      4106: }
                   4107: 
1.1056.4.5  raeburn  4108: sub update_released_required {
                   4109:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4110:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4111:         $cid = $env{'request.course.id'};
                   4112:         $cdom = $env{'course.'.$cid.'.domain'};
                   4113:         $cnum = $env{'course.'.$cid.'.num'};
                   4114:         $chome = $env{'course.'.$cid.'.home'};
                   4115:     }
                   4116:     if ($needsrelease) {
                   4117:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4118:         my $needsupdate;
                   4119:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4120:             $needsupdate = 1;
                   4121:         } else {
                   4122:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4123:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4124:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4125:                 $needsupdate = 1;
                   4126:             }
                   4127:         }
                   4128:         if ($needsupdate) {
                   4129:             my %needshash = (
                   4130:                              'internal.releaserequired' => $needsrelease,
                   4131:                             );
                   4132:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4133:             if ($putresult eq 'ok') {
                   4134:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4135:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4136:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4137:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4138:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4139:                 }
                   4140:             }
                   4141:         }
                   4142:     }
                   4143:     return;
                   4144: }
                   4145: 
1.461     www      4146: # -------------------------------------------------See if a user is privileged
                   4147: 
                   4148: sub privileged {
                   4149:     my ($username,$domain)=@_;
                   4150:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4151: 			&homeserver($username,$domain));
1.1033    raeburn  4152:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4153:         ($rolesdump =~ /^error:/)) {
                   4154:         return 0;
                   4155:     }
1.461     www      4156:     my $now=time;
                   4157:     if ($rolesdump ne '') {
1.800     albertel 4158:         foreach my $entry (split(/&/,$rolesdump)) {
                   4159: 	    if ($entry!~/^rolesdef_/) {
                   4160: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4161: 		$area=~s/\_\w\w$//;
                   4162: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4163: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4164: 		    my $active=1;
                   4165: 		    if ($tend) {
                   4166: 			if ($tend<$now) { $active=0; }
                   4167: 		    }
                   4168: 		    if ($tstart) {
                   4169: 			if ($tstart>$now) { $active=0; }
                   4170: 		    }
                   4171: 		    if ($active) { return 1; }
                   4172: 		}
                   4173: 	    }
                   4174: 	}
                   4175:     }
                   4176:     return 0;
1.9       www      4177: }
1.1       albertel 4178: 
1.103     harris41 4179: # -------------------------------------------------------- Get user privileges
1.11      www      4180: 
                   4181: sub rolesinit {
                   4182:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4183:     my $now=time;
                   4184:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4185:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4186:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4187:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4188:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4189:         return \%userroles;
                   4190:     }
1.11      www      4191:     my %allroles=();
1.678     raeburn  4192:     my %allgroups=();   
                   4193:     my $group_privs;
1.11      www      4194: 
                   4195:     if ($rolesdump ne '') {
1.800     albertel 4196:         foreach my $entry (split(/&/,$rolesdump)) {
                   4197: 	  if ($entry!~/^rolesdef_/) {
                   4198:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4199: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4200:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4201: 	    if ($role=~/^cr/) { 
1.807     albertel 4202: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4203: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4204: 		    ($tend,$tstart)=split('_',$trest);
                   4205: 		} else {
                   4206: 		    $trole=$role;
                   4207: 		}
1.678     raeburn  4208:             } elsif ($role =~ m|^gr/|) {
                   4209:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4210:                 ($trole,$group_privs) = split(/\//,$trole);
                   4211:                 $group_privs = &unescape($group_privs);
1.587     albertel 4212: 	    } else {
                   4213: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4214: 	    }
1.743     albertel 4215: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4216: 					 $username);
                   4217: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4218:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4219:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4220:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4221: 		my $spec=$trole.'.'.$area;
                   4222: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4223: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4224:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4225:                 } elsif ($trole eq 'gr') {
                   4226:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4227: 		} else {
1.567     raeburn  4228:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4229: 		}
1.12      www      4230:             }
1.662     raeburn  4231:           }
1.191     harris41 4232:         }
1.743     albertel 4233:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4234:         $userroles{'user.adv'}    = $adv;
                   4235: 	$userroles{'user.author'} = $author;
1.620     albertel 4236:         $env{'user.adv'}=$adv;
1.11      www      4237:     }
1.743     albertel 4238:     return \%userroles;  
1.11      www      4239: }
                   4240: 
1.567     raeburn  4241: sub set_arearole {
                   4242:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4243: # log the associated role with the area
                   4244:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4245:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4246: }
                   4247: 
                   4248: sub custom_roleprivs {
                   4249:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4250:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4251:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4252:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4253:         my ($rdummy,$roledef)=
                   4254:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4255:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4256:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4257:             if (defined($syspriv)) {
1.1043    raeburn  4258:                 if ($trest =~ /^$match_community$/) {
                   4259:                     $syspriv =~ s/bre\&S//; 
                   4260:                 }
1.567     raeburn  4261:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4262:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4263:             }
                   4264:             if ($tdomain ne '') {
                   4265:                 if (defined($dompriv)) {
                   4266:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4267:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4268:                 }
                   4269:                 if (($trest ne '') && (defined($coursepriv))) {
                   4270:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4271:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4272:                 }
                   4273:             }
                   4274:         }
                   4275:     }
                   4276: }
                   4277: 
1.678     raeburn  4278: sub group_roleprivs {
                   4279:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4280:     my $access = 1;
                   4281:     my $now = time;
                   4282:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4283:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4284:     if ($access) {
1.811     albertel 4285:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4286:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4287:     }
                   4288: }
1.567     raeburn  4289: 
                   4290: sub standard_roleprivs {
                   4291:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4292:     if (defined($pr{$trole.':s'})) {
                   4293:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4294:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4295:     }
                   4296:     if ($tdomain ne '') {
                   4297:         if (defined($pr{$trole.':d'})) {
                   4298:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4299:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4300:         }
                   4301:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4302:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4303:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4304:         }
                   4305:     }
                   4306: }
                   4307: 
                   4308: sub set_userprivs {
1.1056.4.2  raeburn  4309:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4310:     my $author=0;
                   4311:     my $adv=0;
1.678     raeburn  4312:     my %grouproles = ();
                   4313:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4314:         my @groupkeys;
1.1000    raeburn  4315:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4316:             push(@groupkeys,$role);
                   4317:         }
                   4318:         if (ref($groups_roles) eq 'HASH') {
                   4319:             foreach my $key (keys(%{$groups_roles})) {
                   4320:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4321:                     push(@groupkeys,$key);
                   4322:                 }
                   4323:             }
                   4324:         }
                   4325:         if (@groupkeys > 0) {
                   4326:             foreach my $role (@groupkeys) {
                   4327:                 my ($trole,$area,$sec,$extendedarea);
                   4328:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4329:                     $trole = $1;
                   4330:                     $area = $2;
                   4331:                     $sec = $3;
                   4332:                     $extendedarea = $area.$sec;
                   4333:                     if (exists($$allgroups{$area})) {
                   4334:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4335:                             my $spec = $trole.'.'.$extendedarea;
                   4336:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4337:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4338:                         }
1.678     raeburn  4339:                     }
                   4340:                 }
                   4341:             }
                   4342:         }
                   4343:     }
1.800     albertel 4344:     foreach my $group (keys(%grouproles)) {
                   4345:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4346:     }
1.800     albertel 4347:     foreach my $role (keys(%{$allroles})) {
                   4348:         my %thesepriv;
1.941     raeburn  4349:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4350:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4351:             if ($item ne '') {
                   4352:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4353:                 if ($restrictions eq '') {
                   4354:                     $thesepriv{$privilege}='F';
                   4355:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4356:                     $thesepriv{$privilege}.=$restrictions;
                   4357:                 }
                   4358:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4359:             }
                   4360:         }
                   4361:         my $thesestr='';
1.800     albertel 4362:         foreach my $priv (keys(%thesepriv)) {
                   4363: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4364: 	}
                   4365:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4366:     }
                   4367:     return ($author,$adv);
                   4368: }
                   4369: 
1.994     raeburn  4370: sub role_status {
1.1002    raeburn  4371:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4372:     my @pwhere = ();
                   4373:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4374:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4375:         unless (!defined($$role) || $$role eq '') {
                   4376:             $$where=join('.',@pwhere);
                   4377:             $$trolecode=$$role.'.'.$$where;
                   4378:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4379:             $$tstatus='is';
                   4380:             if ($$tstart && $$tstart>$then) {
                   4381:                 $$tstatus='future';
1.1034    raeburn  4382:                 if ($$tstart<$now) {
                   4383:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4384:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4385:                             my (%allroles,%allgroups,$group_privs,
                   4386:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4387:                             my %userroles = (
                   4388:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4389:                             );
1.1056.4.2  raeburn  4390:                             @rolecodes = ('cm');
1.1002    raeburn  4391:                             my $spec=$$role.'.'.$$where;
                   4392:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4393:                             if ($$role =~ /^cr\//) {
                   4394:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4395:                                 push(@rolecodes,'cr');
1.1002    raeburn  4396:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4397:                                 push(@rolecodes,$$role);
1.1002    raeburn  4398:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4399:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4400:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4401:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4402:                                 $group_privs = &unescape($group_privs);
                   4403:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4404:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4405:                                 if (keys(%course_roles) > 0) {
                   4406:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4407:                                     if ($tdomain ne '' && $tnum ne '') {
                   4408:                                         foreach my $key (keys(%course_roles)) {
                   4409:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4410:                                                 my $crsrole = $1;
                   4411:                                                 my $crssec = $2;
                   4412:                                                 if ($crsrole =~ /^cr/) {
                   4413:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4414:                                                         push(@rolecodes,'cr');
                   4415:                                                     }
                   4416:                                                 } else {
                   4417:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4418:                                                         push(@rolecodes,$crsrole);
                   4419:                                                     }
                   4420:                                                 }
                   4421:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4422:                                                 if ($crssec ne '') {
                   4423:                                                     $rolekey .= '/'.$crssec;
                   4424:                                                 }
                   4425:                                                 $rolekey .= './';
                   4426:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4427:                                             }
                   4428:                                         }
                   4429:                                     }
                   4430:                                 }
1.1002    raeburn  4431:                             } else {
1.1056.4.2  raeburn  4432:                                 push(@rolecodes,$$role);
1.1002    raeburn  4433:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4434:                             }
1.1056.4.2  raeburn  4435:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4436:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4437:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4438:                         }
                   4439:                     }
1.1034    raeburn  4440:                     $$tstatus = 'is';
1.1002    raeburn  4441:                 }
1.994     raeburn  4442:             }
                   4443:             if ($$tend) {
                   4444:                 if ($$tend<$then) {
                   4445:                     $$tstatus='expired';
                   4446:                 } elsif ($$tend<$now) {
                   4447:                     $$tstatus='will_not';
                   4448:                 }
                   4449:             }
                   4450:         }
                   4451:     }
                   4452: }
                   4453: 
                   4454: sub check_adhoc_privs {
1.1056.4.12  raeburn  4455:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4456:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4457:     if ($env{$cckey}) {
                   4458:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4459:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4460:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4461:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4462:         }
                   4463:     } else {
1.1056.4.12  raeburn  4464:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4465:     }
                   4466: }
                   4467: 
                   4468: sub set_adhoc_privileges {
                   4469: # role can be cc or ca
1.1056.4.12  raeburn  4470:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4471:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4472:     my $spec = $role.'.'.$area;
                   4473:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4474:                                   $env{'user.name'});
                   4475:     my %ccrole = ();
                   4476:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4477:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4478:     &appenv(\%userroles,[$role,'cm']);
                   4479:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4480:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4481:         &appenv( {'request.role'        => $spec,
                   4482:                   'request.role.domain' => $dcdom,
                   4483:                   'request.course.sec'  => ''
                   4484:                  }
                   4485:                );
                   4486:         my $tadv=0;
                   4487:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4488:         &appenv({'request.role.adv'    => $tadv});
                   4489:     }
1.994     raeburn  4490: }
                   4491: 
1.12      www      4492: # --------------------------------------------------------------- get interface
                   4493: 
                   4494: sub get {
1.131     albertel 4495:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4496:    my $items='';
1.800     albertel 4497:    foreach my $item (@$storearr) {
                   4498:        $items.=&escape($item).'&';
1.191     harris41 4499:    }
1.12      www      4500:    $items=~s/\&$//;
1.620     albertel 4501:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4502:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4503:    my $uhome=&homeserver($uname,$udomain);
                   4504: 
1.133     albertel 4505:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4506:    my @pairs=split(/\&/,$rep);
1.273     albertel 4507:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4508:      return @pairs;
                   4509:    }
1.15      www      4510:    my %returnhash=();
1.42      www      4511:    my $i=0;
1.800     albertel 4512:    foreach my $item (@$storearr) {
                   4513:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4514:       $i++;
1.191     harris41 4515:    }
1.15      www      4516:    return %returnhash;
1.27      www      4517: }
                   4518: 
                   4519: # --------------------------------------------------------------- del interface
                   4520: 
                   4521: sub del {
1.133     albertel 4522:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4523:    my $items='';
1.800     albertel 4524:    foreach my $item (@$storearr) {
                   4525:        $items.=&escape($item).'&';
1.191     harris41 4526:    }
1.984     neumanie 4527: 
1.27      www      4528:    $items=~s/\&$//;
1.620     albertel 4529:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4530:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4531:    my $uhome=&homeserver($uname,$udomain);
                   4532:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4533: }
                   4534: 
                   4535: # -------------------------------------------------------------- dump interface
                   4536: 
                   4537: sub dump {
1.1056.4.10  raeburn  4538:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4539:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4540:     if (!$uname) { $uname=$env{'user.name'}; }
                   4541:     my $uhome=&homeserver($uname,$udomain);
                   4542:     if ($regexp) {
                   4543: 	$regexp=&escape($regexp);
                   4544:     } else {
                   4545: 	$regexp='.';
                   4546:     }
1.1056.4.10  raeburn  4547:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4548:     my @pairs=split(/\&/,$rep);
                   4549:     my %returnhash=();
                   4550:     foreach my $item (@pairs) {
                   4551: 	my ($key,$value)=split(/=/,$item,2);
                   4552: 	$key = &unescape($key);
                   4553: 	next if ($key =~ /^error: 2 /);
                   4554: 	$returnhash{$key}=&thaw_unescape($value);
                   4555:     }
                   4556:     return %returnhash;
1.407     www      4557: }
                   4558: 
1.717     albertel 4559: # --------------------------------------------------------- dumpstore interface
                   4560: 
                   4561: sub dumpstore {
                   4562:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4563:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4564:    if (!$uname) { $uname=$env{'user.name'}; }
                   4565:    my $uhome=&homeserver($uname,$udomain);
                   4566:    if ($regexp) {
                   4567:        $regexp=&escape($regexp);
                   4568:    } else {
                   4569:        $regexp='.';
                   4570:    }
                   4571:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4572:    my @pairs=split(/\&/,$rep);
                   4573:    my %returnhash=();
                   4574:    foreach my $item (@pairs) {
                   4575:        my ($key,$value)=split(/=/,$item,2);
                   4576:        next if ($key =~ /^error: 2 /);
                   4577:        $returnhash{$key}=&thaw_unescape($value);
                   4578:    }
                   4579:    return %returnhash;
1.717     albertel 4580: }
                   4581: 
1.407     www      4582: # -------------------------------------------------------------- keys interface
                   4583: 
                   4584: sub getkeys {
                   4585:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4586:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4587:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4588:    my $uhome=&homeserver($uname,$udomain);
                   4589:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4590:    my @keyarray=();
1.800     albertel 4591:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4592:       next if ($key =~ /^error: 2 /);
1.800     albertel 4593:       push(@keyarray,&unescape($key));
1.407     www      4594:    }
                   4595:    return @keyarray;
1.318     matthew  4596: }
                   4597: 
1.319     matthew  4598: # --------------------------------------------------------------- currentdump
                   4599: sub currentdump {
1.328     matthew  4600:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4601:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4602:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4603:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4604:    my $uhome = &homeserver($sname,$sdom);
                   4605:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4606:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4607:    #
1.318     matthew  4608:    my %returnhash=();
1.319     matthew  4609:    #
                   4610:    if ($rep eq "unknown_cmd") { 
                   4611:        # an old lond will not know currentdump
                   4612:        # Do a dump and make it look like a currentdump
1.822     albertel 4613:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4614:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4615:        my %hash = @tmp;
                   4616:        @tmp=();
1.424     matthew  4617:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4618:    } else {
                   4619:        my @pairs=split(/\&/,$rep);
1.800     albertel 4620:        foreach my $pair (@pairs) {
                   4621:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4622:            my ($symb,$param) = split(/:/,$key);
                   4623:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4624:                                                         &thaw_unescape($value);
1.319     matthew  4625:        }
1.191     harris41 4626:    }
1.12      www      4627:    return %returnhash;
1.424     matthew  4628: }
                   4629: 
                   4630: sub convert_dump_to_currentdump{
                   4631:     my %hash = %{shift()};
                   4632:     my %returnhash;
                   4633:     # Code ripped from lond, essentially.  The only difference
                   4634:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4635:     # we might run in to problems with parameter names =~ /^v\./
                   4636:     while (my ($key,$value) = each(%hash)) {
                   4637:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4638: 	$symb  = &unescape($symb);
                   4639: 	$param = &unescape($param);
1.424     matthew  4640:         next if ($v eq 'version' || $symb eq 'keys');
                   4641:         next if (exists($returnhash{$symb}) &&
                   4642:                  exists($returnhash{$symb}->{$param}) &&
                   4643:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4644:         $returnhash{$symb}->{$param}=$value;
                   4645:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4646:     }
                   4647:     #
                   4648:     # Remove all of the keys in the hashes which keep track of
                   4649:     # the version of the parameter.
                   4650:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4651:         # use a foreach because we are going to delete from the hash.
                   4652:         foreach my $key (keys(%$param_hash)) {
                   4653:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4654:         }
                   4655:     }
                   4656:     return \%returnhash;
1.12      www      4657: }
                   4658: 
1.627     albertel 4659: # ------------------------------------------------------ critical inc interface
                   4660: 
                   4661: sub cinc {
                   4662:     return &inc(@_,'critical');
                   4663: }
                   4664: 
1.449     matthew  4665: # --------------------------------------------------------------- inc interface
                   4666: 
                   4667: sub inc {
1.627     albertel 4668:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4669:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4670:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4671:     my $uhome=&homeserver($uname,$udomain);
                   4672:     my $items='';
                   4673:     if (! ref($store)) {
                   4674:         # got a single value, so use that instead
                   4675:         $items = &escape($store).'=&';
                   4676:     } elsif (ref($store) eq 'SCALAR') {
                   4677:         $items = &escape($$store).'=&';        
                   4678:     } elsif (ref($store) eq 'ARRAY') {
                   4679:         $items = join('=&',map {&escape($_);} @{$store});
                   4680:     } elsif (ref($store) eq 'HASH') {
                   4681:         while (my($key,$value) = each(%{$store})) {
                   4682:             $items.= &escape($key).'='.&escape($value).'&';
                   4683:         }
                   4684:     }
                   4685:     $items=~s/\&$//;
1.627     albertel 4686:     if ($critical) {
                   4687: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4688:     } else {
                   4689: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4690:     }
1.449     matthew  4691: }
                   4692: 
1.12      www      4693: # --------------------------------------------------------------- put interface
                   4694: 
                   4695: sub put {
1.134     albertel 4696:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4697:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4698:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4699:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4700:    my $items='';
1.800     albertel 4701:    foreach my $item (keys(%$storehash)) {
                   4702:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4703:    }
1.12      www      4704:    $items=~s/\&$//;
1.134     albertel 4705:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4706: }
                   4707: 
1.631     albertel 4708: # ------------------------------------------------------------ newput interface
                   4709: 
                   4710: sub newput {
                   4711:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4712:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4713:    if (!$uname) { $uname=$env{'user.name'}; }
                   4714:    my $uhome=&homeserver($uname,$udomain);
                   4715:    my $items='';
                   4716:    foreach my $key (keys(%$storehash)) {
                   4717:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4718:    }
                   4719:    $items=~s/\&$//;
                   4720:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4721: }
                   4722: 
                   4723: # ---------------------------------------------------------  putstore interface
                   4724: 
1.524     raeburn  4725: sub putstore {
1.715     albertel 4726:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4727:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4728:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4729:    my $uhome=&homeserver($uname,$udomain);
                   4730:    my $items='';
1.715     albertel 4731:    foreach my $key (keys(%$storehash)) {
                   4732:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4733:    }
1.715     albertel 4734:    $items=~s/\&$//;
1.716     albertel 4735:    my $esc_symb=&escape($symb);
                   4736:    my $esc_v=&escape($version);
1.715     albertel 4737:    my $reply =
1.716     albertel 4738:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4739: 	      $uhome);
                   4740:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4741:        # gfall back to way things use to be done
1.715     albertel 4742:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4743: 			    $uname);
1.524     raeburn  4744:    }
1.715     albertel 4745:    return $reply;
                   4746: }
                   4747: 
                   4748: sub old_putstore {
1.716     albertel 4749:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4750:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4751:     if (!$uname) { $uname=$env{'user.name'}; }
                   4752:     my $uhome=&homeserver($uname,$udomain);
                   4753:     my %newstorehash;
1.800     albertel 4754:     foreach my $item (keys(%$storehash)) {
                   4755: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4756: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4757:     }
                   4758:     my $items='';
                   4759:     my %allitems = ();
1.800     albertel 4760:     foreach my $item (keys(%newstorehash)) {
                   4761: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4762: 	    my $key = $1.':keys:'.$2;
                   4763: 	    $allitems{$key} .= $3.':';
                   4764: 	}
1.800     albertel 4765: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4766:     }
1.800     albertel 4767:     foreach my $item (keys(%allitems)) {
                   4768: 	$allitems{$item} =~ s/\:$//;
                   4769: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4770:     }
                   4771:     $items=~s/\&$//;
                   4772:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4773: }
                   4774: 
1.47      www      4775: # ------------------------------------------------------ critical put interface
                   4776: 
                   4777: sub cput {
1.134     albertel 4778:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4779:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4780:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4781:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4782:    my $items='';
1.800     albertel 4783:    foreach my $item (keys(%$storehash)) {
                   4784:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4785:    }
1.47      www      4786:    $items=~s/\&$//;
1.134     albertel 4787:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4788: }
                   4789: 
                   4790: # -------------------------------------------------------------- eget interface
                   4791: 
                   4792: sub eget {
1.133     albertel 4793:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4794:    my $items='';
1.800     albertel 4795:    foreach my $item (@$storearr) {
                   4796:        $items.=&escape($item).'&';
1.191     harris41 4797:    }
1.12      www      4798:    $items=~s/\&$//;
1.620     albertel 4799:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4800:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4801:    my $uhome=&homeserver($uname,$udomain);
                   4802:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4803:    my @pairs=split(/\&/,$rep);
                   4804:    my %returnhash=();
1.42      www      4805:    my $i=0;
1.800     albertel 4806:    foreach my $item (@$storearr) {
                   4807:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4808:       $i++;
1.191     harris41 4809:    }
1.12      www      4810:    return %returnhash;
                   4811: }
                   4812: 
1.667     albertel 4813: # ------------------------------------------------------------ tmpput interface
                   4814: sub tmpput {
1.802     raeburn  4815:     my ($storehash,$server,$context)=@_;
1.667     albertel 4816:     my $items='';
1.800     albertel 4817:     foreach my $item (keys(%$storehash)) {
                   4818: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4819:     }
                   4820:     $items=~s/\&$//;
1.802     raeburn  4821:     if (defined($context)) {
                   4822:         $items .= ':'.&escape($context);
                   4823:     }
1.667     albertel 4824:     return &reply("tmpput:$items",$server);
                   4825: }
                   4826: 
                   4827: # ------------------------------------------------------------ tmpget interface
                   4828: sub tmpget {
1.688     albertel 4829:     my ($token,$server)=@_;
                   4830:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4831:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4832:     my %returnhash;
                   4833:     foreach my $item (split(/\&/,$rep)) {
                   4834: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4835:         next if ($key =~ /^error: 2 /);
1.667     albertel 4836: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4837:     }
                   4838:     return %returnhash;
                   4839: }
                   4840: 
1.688     albertel 4841: # ------------------------------------------------------------ tmpget interface
                   4842: sub tmpdel {
                   4843:     my ($token,$server)=@_;
                   4844:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4845:     return &reply("tmpdel:$token",$server);
                   4846: }
                   4847: 
1.765     albertel 4848: # -------------------------------------------------- portfolio access checking
                   4849: 
                   4850: sub portfolio_access {
1.766     albertel 4851:     my ($requrl) = @_;
1.765     albertel 4852:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4853:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4854:     if ($result) {
                   4855:         my %setters;
                   4856:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4857:             my ($startblock,$endblock) =
                   4858:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4859:             if ($startblock && $endblock) {
                   4860:                 return 'B';
                   4861:             }
                   4862:         } else {
                   4863:             my ($startblock,$endblock) =
                   4864:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4865:             if ($startblock && $endblock) {
                   4866:                 return 'B';
                   4867:             }
                   4868:         }
                   4869:     }
1.765     albertel 4870:     if ($result eq 'ok') {
1.766     albertel 4871:        return 'F';
1.765     albertel 4872:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4873:        return 'A';
1.765     albertel 4874:     }
1.766     albertel 4875:     return '';
1.765     albertel 4876: }
                   4877: 
                   4878: sub get_portfolio_access {
1.767     albertel 4879:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4880: 
                   4881:     if (!ref($access_hash)) {
                   4882: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4883: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4884: 						   $file_name);
                   4885: 	$access_hash = $access_controls{$file_name};
                   4886:     }
                   4887: 
1.765     albertel 4888:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4889:     my $now = time;
                   4890:     if (ref($access_hash) eq 'HASH') {
                   4891:         foreach my $key (keys(%{$access_hash})) {
                   4892:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4893:             if ($start > $now) {
                   4894:                 next;
                   4895:             }
                   4896:             if ($end && $end<$now) {
                   4897:                 next;
                   4898:             }
                   4899:             if ($scope eq 'public') {
                   4900:                 $public = $key;
                   4901:                 last;
                   4902:             } elsif ($scope eq 'guest') {
                   4903:                 $guest = $key;
                   4904:             } elsif ($scope eq 'domains') {
                   4905:                 push(@domains,$key);
                   4906:             } elsif ($scope eq 'users') {
                   4907:                 push(@users,$key);
                   4908:             } elsif ($scope eq 'course') {
                   4909:                 push(@courses,$key);
                   4910:             } elsif ($scope eq 'group') {
                   4911:                 push(@groups,$key);
                   4912:             }
                   4913:         }
                   4914:         if ($public) {
                   4915:             return 'ok';
                   4916:         }
                   4917:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4918:             if ($guest) {
                   4919:                 return $guest;
                   4920:             }
                   4921:         } else {
                   4922:             if (@domains > 0) {
                   4923:                 foreach my $domkey (@domains) {
                   4924:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4925:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4926:                             return 'ok';
                   4927:                         }
                   4928:                     }
                   4929:                 }
                   4930:             }
                   4931:             if (@users > 0) {
                   4932:                 foreach my $userkey (@users) {
1.865     raeburn  4933:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4934:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4935:                             if (ref($item) eq 'HASH') {
                   4936:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4937:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4938:                                     return 'ok';
                   4939:                                 }
                   4940:                             }
                   4941:                         }
                   4942:                     } 
1.765     albertel 4943:                 }
                   4944:             }
                   4945:             my %roleshash;
                   4946:             my @courses_and_groups = @courses;
                   4947:             push(@courses_and_groups,@groups); 
                   4948:             if (@courses_and_groups > 0) {
                   4949:                 my (%allgroups,%allroles); 
                   4950:                 my ($start,$end,$role,$sec,$group);
                   4951:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4952:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4953:                         my $cid = $2.'_'.$3; 
                   4954:                         if ($1 eq 'gr') {
                   4955:                             $group = $4;
                   4956:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4957:                         } else {
                   4958:                             if ($4 eq '') {
                   4959:                                 $sec = 'none';
                   4960:                             } else {
                   4961:                                 $sec = $4;
                   4962:                             }
                   4963:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4964:                         }
1.811     albertel 4965:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4966:                         my $cid = $2.'_'.$3;
                   4967:                         if ($4 eq '') {
                   4968:                             $sec = 'none';
                   4969:                         } else {
                   4970:                             $sec = $4;
                   4971:                         }
                   4972:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4973:                     }
                   4974:                 }
                   4975:                 if (keys(%allroles) == 0) {
                   4976:                     return;
                   4977:                 }
                   4978:                 foreach my $key (@courses_and_groups) {
                   4979:                     my %content = %{$$access_hash{$key}};
                   4980:                     my $cnum = $content{'number'};
                   4981:                     my $cdom = $content{'domain'};
                   4982:                     my $cid = $cdom.'_'.$cnum;
                   4983:                     if (!exists($allroles{$cid})) {
                   4984:                         next;
                   4985:                     }    
                   4986:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4987:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4988:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4989:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4990:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4991:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4992:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4993:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4994:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4995:                                         if (grep/^all$/,@sections) {
                   4996:                                             return 'ok';
                   4997:                                         } else {
                   4998:                                             if (grep/^$sec$/,@sections) {
                   4999:                                                 return 'ok';
                   5000:                                             }
                   5001:                                         }
                   5002:                                     }
                   5003:                                 }
                   5004:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5005:                                     if (grep/^none$/,@groups) {
                   5006:                                         return 'ok';
                   5007:                                     }
                   5008:                                 } else {
                   5009:                                     if (grep/^all$/,@groups) {
                   5010:                                         return 'ok';
                   5011:                                     } 
                   5012:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5013:                                         if (grep/^$group$/,@groups) {
                   5014:                                             return 'ok';
                   5015:                                         }
                   5016:                                     }
                   5017:                                 } 
                   5018:                             }
                   5019:                         }
                   5020:                     }
                   5021:                 }
                   5022:             }
                   5023:             if ($guest) {
                   5024:                 return $guest;
                   5025:             }
                   5026:         }
                   5027:     }
                   5028:     return;
                   5029: }
                   5030: 
                   5031: sub course_group_datechecker {
                   5032:     my ($dates,$now,$status) = @_;
                   5033:     my ($start,$end) = split(/\./,$dates);
                   5034:     if (!$start && !$end) {
                   5035:         return 'ok';
                   5036:     }
                   5037:     if (grep/^active$/,@{$status}) {
                   5038:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5039:             return 'ok';
                   5040:         }
                   5041:     }
                   5042:     if (grep/^previous$/,@{$status}) {
                   5043:         if ($end > $now ) {
                   5044:             return 'ok';
                   5045:         }
                   5046:     }
                   5047:     if (grep/^future$/,@{$status}) {
                   5048:         if ($start > $now) {
                   5049:             return 'ok';
                   5050:         }
                   5051:     }
                   5052:     return; 
                   5053: }
                   5054: 
                   5055: sub parse_portfolio_url {
                   5056:     my ($url) = @_;
                   5057: 
                   5058:     my ($type,$udom,$unum,$group,$file_name);
                   5059:     
1.823     albertel 5060:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5061: 	$type = 1;
                   5062:         $udom = $1;
                   5063:         $unum = $2;
                   5064:         $file_name = $3;
1.823     albertel 5065:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5066: 	$type = 2;
                   5067:         $udom = $1;
                   5068:         $unum = $2;
                   5069:         $group = $3;
                   5070:         $file_name = $3.'/'.$4;
                   5071:     }
                   5072:     if (wantarray) {
                   5073: 	return ($type,$udom,$unum,$file_name,$group);
                   5074:     }
                   5075:     return $type;
                   5076: }
                   5077: 
                   5078: sub is_portfolio_url {
                   5079:     my ($url) = @_;
                   5080:     return scalar(&parse_portfolio_url($url));
                   5081: }
                   5082: 
1.798     raeburn  5083: sub is_portfolio_file {
                   5084:     my ($file) = @_;
1.820     raeburn  5085:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5086:         return 1;
                   5087:     }
                   5088:     return;
                   5089: }
                   5090: 
1.976     raeburn  5091: sub usertools_access {
1.1056.4.9  raeburn  5092:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5093:     my ($access,%tools);
                   5094:     if ($context eq '') {
                   5095:         $context = 'tools';
                   5096:     }
                   5097:     if ($context eq 'requestcourses') {
                   5098:         %tools = (
                   5099:                       official   => 1,
                   5100:                       unofficial => 1,
1.1006    raeburn  5101:                       community  => 1,
1.985     raeburn  5102:                  );
                   5103:     } else {
                   5104:         %tools = (
                   5105:                       aboutme   => 1,
                   5106:                       blog      => 1,
                   5107:                       portfolio => 1,
                   5108:                  );
                   5109:     }
1.976     raeburn  5110:     return if (!defined($tools{$tool}));
                   5111: 
                   5112:     if ((!defined($udom)) || (!defined($uname))) {
                   5113:         $udom = $env{'user.domain'};
                   5114:         $uname = $env{'user.name'};
                   5115:     }
                   5116: 
1.978     raeburn  5117:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5118:         if ($action ne 'reload') {
1.985     raeburn  5119:             if ($context eq 'requestcourses') {
                   5120:                 return $env{'environment.canrequest.'.$tool};
                   5121:             } else {
                   5122:                 return $env{'environment.availabletools.'.$tool};
                   5123:             }
                   5124:         }
1.976     raeburn  5125:     }
                   5126: 
                   5127:     my ($toolstatus,$inststatus);
                   5128: 
1.985     raeburn  5129:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5130:          ($action ne 'reload')) {
                   5131:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5132:         $inststatus = $env{'environment.inststatus'};
                   5133:     } else {
1.1056.4.9  raeburn  5134:         if (ref($userenvref) eq 'HASH') {
                   5135:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5136:             $inststatus = $userenvref->{'inststatus'};
                   5137:         } else {
                   5138:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5139:             $toolstatus = $userenv{$context.'.'.$tool};
                   5140:             $inststatus = $userenv{'inststatus'};
                   5141:         }
1.976     raeburn  5142:     }
                   5143: 
                   5144:     if ($toolstatus ne '') {
                   5145:         if ($toolstatus) {
                   5146:             $access = 1;
                   5147:         } else {
                   5148:             $access = 0;
                   5149:         }
                   5150:         return $access;
                   5151:     }
                   5152: 
1.1056.4.9  raeburn  5153:     my ($is_adv,%domdef);
                   5154:     if (ref($is_advref) eq 'HASH') {
                   5155:         $is_adv = $is_advref->{'is_adv'};
                   5156:     } else {
                   5157:         $is_adv = &is_advanced_user($udom,$uname);
                   5158:     }
                   5159:     if (ref($domdefref) eq 'HASH') {
                   5160:         %domdef = %{$domdefref};
                   5161:     } else {
                   5162:         %domdef = &get_domain_defaults($udom);
                   5163:     }
1.976     raeburn  5164:     if (ref($domdef{$tool}) eq 'HASH') {
                   5165:         if ($is_adv) {
                   5166:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5167:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5168:                     $access = 1;
                   5169:                 } else {
                   5170:                     $access = 0;
                   5171:                 }
                   5172:                 return $access;
                   5173:             }
                   5174:         }
                   5175:         if ($inststatus ne '') {
                   5176:             my ($hasaccess,$hasnoaccess);
                   5177:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5178:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5179:                     if ($domdef{$tool}{$affiliation}) {
                   5180:                         $hasaccess = 1;
                   5181:                     } else {
                   5182:                         $hasnoaccess = 1;
                   5183:                     }
                   5184:                 }
                   5185:             }
                   5186:             if ($hasaccess || $hasnoaccess) {
                   5187:                 if ($hasaccess) {
                   5188:                     $access = 1;
                   5189:                 } elsif ($hasnoaccess) {
                   5190:                     $access = 0; 
                   5191:                 }
                   5192:                 return $access;
                   5193:             }
                   5194:         } else {
                   5195:             if ($domdef{$tool}{'default'} ne '') {
                   5196:                 if ($domdef{$tool}{'default'}) {
                   5197:                     $access = 1;
                   5198:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5199:                     $access = 0;
                   5200:                 }
                   5201:                 return $access;
                   5202:             }
                   5203:         }
                   5204:     } else {
1.985     raeburn  5205:         if ($context eq 'tools') {
                   5206:             $access = 1;
                   5207:         } else {
                   5208:             $access = 0;
                   5209:         }
1.976     raeburn  5210:         return $access;
                   5211:     }
                   5212: }
                   5213: 
1.1050    raeburn  5214: sub is_course_owner {
                   5215:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5216:     if (($udom eq '') || ($uname eq '')) {
                   5217:         $udom = $env{'user.domain'};
                   5218:         $uname = $env{'user.name'};
                   5219:     }
                   5220:     unless (($udom eq '') || ($uname eq '')) {
                   5221:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5222:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5223:                 return 1;
                   5224:             } else {
                   5225:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5226:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5227:                     return 1;
                   5228:                 }
                   5229:             }
                   5230:         }
                   5231:     }
                   5232:     return;
                   5233: }
                   5234: 
1.976     raeburn  5235: sub is_advanced_user {
                   5236:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5237:     if ($udom ne '' && $uname ne '') {
                   5238:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5239:             return $env{'user.adv'};
                   5240:         }
                   5241:     }
1.976     raeburn  5242:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5243:     my %allroles;
                   5244:     my $is_adv;
                   5245:     foreach my $role (keys(%roleshash)) {
                   5246:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5247:         my $area = '/'.$tdomain.'/'.$trest;
                   5248:         if ($sec ne '') {
                   5249:             $area .= '/'.$sec;
                   5250:         }
                   5251:         if (($area ne '') && ($trole ne '')) {
                   5252:             my $spec=$trole.'.'.$area;
                   5253:             if ($trole =~ /^cr\//) {
                   5254:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5255:             } elsif ($trole ne 'gr') {
                   5256:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5257:             }
                   5258:         }
                   5259:     }
                   5260:     foreach my $role (keys(%allroles)) {
                   5261:         last if ($is_adv);
                   5262:         foreach my $item (split(/:/,$allroles{$role})) {
                   5263:             if ($item ne '') {
                   5264:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5265:                 if ($privilege eq 'adv') {
                   5266:                     $is_adv = 1;
                   5267:                     last;
                   5268:                 }
                   5269:             }
                   5270:         }
                   5271:     }
                   5272:     return $is_adv;
                   5273: }
1.798     raeburn  5274: 
1.1035    raeburn  5275: sub check_can_request {
1.1036    raeburn  5276:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5277:     my $canreq = 0;
                   5278:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5279:     my @options = ('approval','validate','autolimit');
                   5280:     my $optregex = join('|',@options);
                   5281:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5282:         foreach my $type (@{$types}) {
                   5283:             if (&usertools_access($env{'user.name'},
                   5284:                                   $env{'user.domain'},
                   5285:                                   $type,undef,'requestcourses')) {
                   5286:                 $canreq ++;
1.1036    raeburn  5287:                 if (ref($request_domains) eq 'HASH') {
                   5288:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5289:                 }
1.1035    raeburn  5290:                 if ($dom eq $env{'user.domain'}) {
                   5291:                     $can_request->{$type} = 1;
                   5292:                 }
                   5293:             }
                   5294:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5295:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5296:                 if (@curr > 0) {
1.1036    raeburn  5297:                     foreach my $item (@curr) {
                   5298:                         if (ref($request_domains) eq 'HASH') {
                   5299:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5300:                             if ($otherdom ne '') {
                   5301:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5302:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5303:                                         push(@{$request_domains->{$type}},$otherdom);
                   5304:                                     }
                   5305:                                 } else {
                   5306:                                     push(@{$request_domains->{$type}},$otherdom);
                   5307:                                 }
                   5308:                             }
                   5309:                         }
                   5310:                     }
                   5311:                     unless($dom eq $env{'user.domain'}) {
                   5312:                         $canreq ++;
1.1035    raeburn  5313:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5314:                             $can_request->{$type} = 1;
                   5315:                         }
                   5316:                     }
                   5317:                 }
                   5318:             }
                   5319:         }
                   5320:     }
                   5321:     return $canreq;
                   5322: }
                   5323: 
1.341     www      5324: # ---------------------------------------------- Custom access rule evaluation
                   5325: 
                   5326: sub customaccess {
                   5327:     my ($priv,$uri)=@_;
1.807     albertel 5328:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5329:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5330:     $udom = &LONCAPA::clean_domain($udom);
                   5331:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5332:     my $access=0;
1.800     albertel 5333:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5334: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5335: 	if ($type eq 'user') {
                   5336: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5337: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5338: 		if ($tdom) {
                   5339: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5340: 		}
1.896     albertel 5341: 		if ($tuname) {
                   5342: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5343: 		}
                   5344: 		$access=($effect eq 'allow');
                   5345: 		last;
                   5346: 	    }
                   5347: 	} else {
                   5348: 	    if ($role) {
                   5349: 		if ($role ne $urole) { next; }
                   5350: 	    }
                   5351: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5352: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5353: 		if ($tdom) {
                   5354: 		    if ($tdom ne $udom) { next; }
                   5355: 		}
                   5356: 		if ($tcrs) {
                   5357: 		    if ($tcrs ne $ucrs) { next; }
                   5358: 		}
                   5359: 		if ($tsec) {
                   5360: 		    if ($tsec ne $usec) { next; }
                   5361: 		}
                   5362: 		$access=($effect eq 'allow');
                   5363: 		last;
                   5364: 	    }
                   5365: 	    if ($realm eq '' && $role eq '') {
                   5366: 		$access=($effect eq 'allow');
                   5367: 	    }
1.402     bowersj2 5368: 	}
1.341     www      5369:     }
                   5370:     return $access;
                   5371: }
                   5372: 
1.103     harris41 5373: # ------------------------------------------------- Check for a user privilege
1.12      www      5374: 
                   5375: sub allowed {
1.810     raeburn  5376:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5377:     my $ver_orguri=$uri;
1.439     www      5378:     $uri=&deversion($uri);
1.152     www      5379:     my $orguri=$uri;
1.52      www      5380:     $uri=&declutter($uri);
1.809     raeburn  5381: 
1.810     raeburn  5382:     if ($priv eq 'evb') {
                   5383: # Evade communication block restrictions for specified role in a course
                   5384:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5385:             return $1;
                   5386:         } else {
                   5387:             return;
                   5388:         }
                   5389:     }
                   5390: 
1.620     albertel 5391:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5392: # Free bre access to adm and meta resources
1.775     albertel 5393:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5394: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5395: 	&& ($priv eq 'bre')) {
1.14      www      5396: 	return 'F';
1.159     www      5397:     }
                   5398: 
1.545     banghart 5399: # Free bre access to user's own portfolio contents
1.714     raeburn  5400:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5401:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5402: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5403:         my %setters;
                   5404:         my ($startblock,$endblock) = 
                   5405:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5406:         if ($startblock && $endblock) {
                   5407:             return 'B';
                   5408:         } else {
                   5409:             return 'F';
                   5410:         }
1.545     banghart 5411:     }
                   5412: 
1.762     raeburn  5413: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5414:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5415:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5416:         if (exists($env{'request.course.id'})) {
                   5417:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5418:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5419:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5420:                 my $courseprivid=$env{'request.course.id'};
                   5421:                 $courseprivid=~s/\_/\//;
                   5422:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5423:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5424:                     return $1; 
1.762     raeburn  5425:                 } else {
                   5426:                     if ($env{'request.course.sec'}) {
                   5427:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5428:                     }
                   5429:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5430:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5431:                         return $2;
                   5432:                     }
1.714     raeburn  5433:                 }
                   5434:             }
                   5435:         }
                   5436:     }
                   5437: 
1.159     www      5438: # Free bre to public access
                   5439: 
                   5440:     if ($priv eq 'bre') {
1.238     www      5441:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5442: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5443:            return 'F'; 
                   5444:         }
1.238     www      5445:         if ($copyright eq 'priv') {
                   5446:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5447: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5448: 		return '';
                   5449:             }
                   5450:         }
                   5451:         if ($copyright eq 'domain') {
                   5452:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5453: 	    unless (($env{'user.domain'} eq $1) ||
                   5454:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5455: 		return '';
                   5456:             }
1.262     matthew  5457:         }
1.620     albertel 5458:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5459:             # Library role, so allow browsing of resources in this domain.
                   5460:             return 'F';
1.238     www      5461:         }
1.341     www      5462:         if ($copyright eq 'custom') {
                   5463: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5464:         }
1.14      www      5465:     }
1.264     matthew  5466:     # Domain coordinator is trying to create a course
1.620     albertel 5467:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5468:         # uri is the requested domain in this case.
                   5469:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5470:         # a role of dc for the domain in question.
1.620     albertel 5471:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5472:     }
1.29      www      5473: 
1.52      www      5474:     my $thisallowed='';
                   5475:     my $statecond=0;
                   5476:     my $courseprivid='';
                   5477: 
1.1039    raeburn  5478:     my $ownaccess;
1.1043    raeburn  5479:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5480:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5481:         if ($uri eq '') {
                   5482:             $ownaccess = 1;
                   5483:         } else {
                   5484:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5485:                 my $udom = $env{'user.domain'};
                   5486:                 my $uname = $env{'user.name'};
                   5487:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5488:                     $ownaccess = 1;
1.1040    raeburn  5489:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5490:                     unless ($uri =~ m{\.\./}) {
                   5491:                         $ownaccess = 1;
                   5492:                     }
                   5493:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5494:                     my $now = time;
                   5495:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5496:                         my $adom = $1;
                   5497:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5498:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5499:                                 my ($start,$end) = split('.',$env{$key});
                   5500:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5501:                                     $ownaccess = 1;
                   5502:                                     last;
                   5503:                                 }
                   5504:                             }
                   5505:                         }
                   5506:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5507:                         my $adom = $1;
                   5508:                         my $aname = $2;
1.1042    raeburn  5509:                         foreach my $role ('ca','aa') { 
                   5510:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5511:                                 my ($start,$end) =
                   5512:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5513:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5514:                                     $ownaccess = 1;
                   5515:                                     last;
                   5516:                                 }
1.1039    raeburn  5517:                             }
                   5518:                         }
                   5519:                     }
                   5520:                 }
                   5521:             }
                   5522:         }
                   5523:     }
                   5524: 
1.52      www      5525: # Course
                   5526: 
1.620     albertel 5527:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5528:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5529:             $thisallowed.=$1;
                   5530:         }
1.52      www      5531:     }
1.29      www      5532: 
1.52      www      5533: # Domain
                   5534: 
1.620     albertel 5535:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5536:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5537:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5538:             $thisallowed.=$1;
                   5539:         }
1.12      www      5540:     }
1.52      www      5541: 
                   5542: # Course: uri itself is a course
1.66      www      5543:     my $courseuri=$uri;
                   5544:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5545:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5546: 
1.620     albertel 5547:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5548:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5549:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5550:             $thisallowed.=$1;
                   5551:         }
1.12      www      5552:     }
1.29      www      5553: 
1.665     albertel 5554: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5555: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5556:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5557: 	$thisallowed='';
1.671     raeburn  5558:         my ($match)=&is_on_map($uri);
                   5559:         if ($match) {
                   5560:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5561:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5562:                 $thisallowed.=$1;
                   5563:             }
                   5564:         } else {
1.705     albertel 5565:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5566:             if ($refuri) {
                   5567:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5568:                     $thisallowed='F';
1.671     raeburn  5569:                 } else {
                   5570:                     $refuri=&declutter($refuri);
                   5571:                     my ($match) = &is_on_map($refuri);
                   5572:                     if ($match) {
                   5573:                         $thisallowed='F';
                   5574:                     }
1.669     raeburn  5575:                 }
1.671     raeburn  5576:             }
                   5577:         }
1.314     www      5578:     }
1.492     albertel 5579: 
1.766     albertel 5580:     if ($priv eq 'bre'
                   5581: 	&& $thisallowed ne 'F' 
                   5582: 	&& $thisallowed ne '2'
                   5583: 	&& &is_portfolio_url($uri)) {
                   5584: 	$thisallowed = &portfolio_access($uri);
                   5585:     }
                   5586:     
1.52      www      5587: # Full access at system, domain or course-wide level? Exit.
1.29      www      5588:     if ($thisallowed=~/F/) {
                   5589: 	return 'F';
                   5590:     }
                   5591: 
1.52      www      5592: # If this is generating or modifying users, exit with special codes
1.29      www      5593: 
1.643     www      5594:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5595: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5596: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5597: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5598: 	    unless ($auname) { return $thisallowed; }
                   5599: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5600: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5601: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5602: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5603: 	}
1.52      www      5604: 	return $thisallowed;
                   5605:     }
                   5606: #
1.103     harris41 5607: # Gathered so far: system, domain and course wide privileges
1.52      www      5608: #
                   5609: # Course: See if uri or referer is an individual resource that is part of 
                   5610: # the course
                   5611: 
1.620     albertel 5612:     if ($env{'request.course.id'}) {
1.232     www      5613: 
1.620     albertel 5614:        $courseprivid=$env{'request.course.id'};
                   5615:        if ($env{'request.course.sec'}) {
                   5616:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5617:        }
                   5618:        $courseprivid=~s/\_/\//;
                   5619:        my $checkreferer=1;
1.232     www      5620:        my ($match,$cond)=&is_on_map($uri);
                   5621:        if ($match) {
                   5622:            $statecond=$cond;
1.620     albertel 5623:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5624:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5625:                $thisallowed.=$1;
                   5626:                $checkreferer=0;
                   5627:            }
1.29      www      5628:        }
1.83      www      5629:        
1.148     www      5630:        if ($checkreferer) {
1.620     albertel 5631: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5632:             unless ($refuri) {
1.800     albertel 5633:                 foreach my $key (keys(%env)) {
                   5634: 		    if ($key=~/^httpref\..*\*/) {
                   5635: 			my $pattern=$key;
1.156     www      5636:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5637:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5638:                         $pattern=~s/\//\\\//g;
1.152     www      5639:                         if ($orguri=~/$pattern/) {
1.800     albertel 5640: 			    $refuri=$env{$key};
1.148     www      5641:                         }
                   5642:                     }
1.191     harris41 5643:                 }
1.148     www      5644:             }
1.232     www      5645: 
1.148     www      5646:          if ($refuri) { 
1.152     www      5647: 	  $refuri=&declutter($refuri);
1.232     www      5648:           my ($match,$cond)=&is_on_map($refuri);
                   5649:             if ($match) {
                   5650:               my $refstatecond=$cond;
1.620     albertel 5651:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5652:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5653:                   $thisallowed.=$1;
1.53      www      5654:                   $uri=$refuri;
                   5655:                   $statecond=$refstatecond;
1.52      www      5656:               }
                   5657:           }
1.148     www      5658:         }
1.29      www      5659:        }
1.52      www      5660:    }
1.29      www      5661: 
1.52      www      5662: #
1.103     harris41 5663: # Gathered now: all privileges that could apply, and condition number
1.52      www      5664: # 
                   5665: #
                   5666: # Full or no access?
                   5667: #
1.29      www      5668: 
1.52      www      5669:     if ($thisallowed=~/F/) {
                   5670: 	return 'F';
                   5671:     }
1.29      www      5672: 
1.52      www      5673:     unless ($thisallowed) {
                   5674:         return '';
                   5675:     }
1.29      www      5676: 
1.52      www      5677: # Restrictions exist, deal with them
                   5678: #
                   5679: #   C:according to course preferences
                   5680: #   R:according to resource settings
                   5681: #   L:unless locked
                   5682: #   X:according to user session state
                   5683: #
                   5684: 
                   5685: # Possibly locked functionality, check all courses
1.54      www      5686: # Locks might take effect only after 10 minutes cache expiration for other
                   5687: # courses, and 2 minutes for current course
1.52      www      5688: 
                   5689:     my $envkey;
                   5690:     if ($thisallowed=~/L/) {
1.1000    raeburn  5691:         foreach $envkey (keys(%env)) {
1.54      www      5692:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5693:                my $courseid=$2;
                   5694:                my $roleid=$1.'.'.$2;
1.92      www      5695:                $courseid=~s/^\///;
1.54      www      5696:                my $expiretime=600;
1.620     albertel 5697:                if ($env{'request.role'} eq $roleid) {
1.54      www      5698: 		  $expiretime=120;
                   5699:                }
                   5700: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5701:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5702:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5703: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5704:                }
1.620     albertel 5705:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5706:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5707: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5708:                        &log($env{'user.domain'},$env{'user.name'},
                   5709:                             $env{'user.home'},
1.57      www      5710:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5711:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5712:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5713: 		       return '';
                   5714:                    }
                   5715:                }
1.620     albertel 5716:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5717:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5718: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5719:                        &log($env{'user.domain'},$env{'user.name'},
                   5720:                             $env{'user.home'},
1.57      www      5721:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5722:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5723:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5724: 		       return '';
                   5725:                    }
                   5726:                }
                   5727: 	   }
1.29      www      5728:        }
1.52      www      5729:     }
                   5730:    
                   5731: #
                   5732: # Rest of the restrictions depend on selected course
                   5733: #
                   5734: 
1.620     albertel 5735:     unless ($env{'request.course.id'}) {
1.766     albertel 5736: 	if ($thisallowed eq 'A') {
                   5737: 	    return 'A';
1.814     raeburn  5738:         } elsif ($thisallowed eq 'B') {
                   5739:             return 'B';
1.766     albertel 5740: 	} else {
                   5741: 	    return '1';
                   5742: 	}
1.52      www      5743:     }
1.29      www      5744: 
1.52      www      5745: #
                   5746: # Now user is definitely in a course
                   5747: #
1.53      www      5748: 
                   5749: 
                   5750: # Course preferences
                   5751: 
                   5752:    if ($thisallowed=~/C/) {
1.620     albertel 5753:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5754:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5755:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5756: 	   =~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5757:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5758: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5759: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5760: 			$env{'request.course.id'});
                   5761: 	   }
1.237     www      5762:            return '';
                   5763:        }
                   5764: 
1.620     albertel 5765:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5766: 	   =~/\Q$unamedom\E/) {
1.1056.4.22  raeburn  5767:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5768: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5769: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5770: 			$env{'request.course.id'});
                   5771: 	   }
1.54      www      5772:            return '';
                   5773:        }
1.53      www      5774:    }
                   5775: 
                   5776: # Resource preferences
                   5777: 
                   5778:    if ($thisallowed=~/R/) {
1.620     albertel 5779:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5780:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5781:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5782: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5783: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5784: 	   }
                   5785: 	   return '';
1.54      www      5786:        }
1.53      www      5787:    }
1.30      www      5788: 
1.246     www      5789: # Restricted by state or randomout?
1.30      www      5790: 
1.52      www      5791:    if ($thisallowed=~/X/) {
1.620     albertel 5792:       if ($env{'acc.randomout'}) {
1.579     albertel 5793: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5794:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5795:             return ''; 
                   5796:          }
1.247     www      5797:       }
                   5798:       if (&condval($statecond)) {
1.52      www      5799: 	 return '2';
                   5800:       } else {
                   5801:          return '';
                   5802:       }
                   5803:    }
1.30      www      5804: 
1.766     albertel 5805:     if ($thisallowed eq 'A') {
                   5806: 	return 'A';
1.814     raeburn  5807:     } elsif ($thisallowed eq 'B') {
                   5808:         return 'B';
1.766     albertel 5809:     }
1.52      www      5810:    return 'F';
1.232     www      5811: }
                   5812: 
1.710     albertel 5813: sub split_uri_for_cond {
                   5814:     my $uri=&deversion(&declutter(shift));
                   5815:     my @uriparts=split(/\//,$uri);
                   5816:     my $filename=pop(@uriparts);
                   5817:     my $pathname=join('/',@uriparts);
                   5818:     return ($pathname,$filename);
                   5819: }
1.232     www      5820: # --------------------------------------------------- Is a resource on the map?
                   5821: 
                   5822: sub is_on_map {
1.710     albertel 5823:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5824:     #Trying to find the conditional for the file
1.620     albertel 5825:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5826: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5827:     if ($match) {
1.289     bowersj2 5828: 	return (1,$1);
                   5829:     } else {
1.434     www      5830: 	return (0,0);
1.289     bowersj2 5831:     }
1.12      www      5832: }
                   5833: 
1.427     www      5834: # --------------------------------------------------------- Get symb from alias
                   5835: 
                   5836: sub get_symb_from_alias {
                   5837:     my $symb=shift;
                   5838:     my ($map,$resid,$url)=&decode_symb($symb);
                   5839: # Already is a symb
                   5840:     if ($url) { return $symb; }
                   5841: # Must be an alias
                   5842:     my $aliassymb='';
                   5843:     my %bighash;
1.620     albertel 5844:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5845:                             &GDBM_READER(),0640)) {
                   5846:         my $rid=$bighash{'mapalias_'.$symb};
                   5847: 	if ($rid) {
                   5848: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5849: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5850: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5851: 	}
                   5852:         untie %bighash;
                   5853:     }
                   5854:     return $aliassymb;
                   5855: }
                   5856: 
1.12      www      5857: # ----------------------------------------------------------------- Define Role
                   5858: 
                   5859: sub definerole {
                   5860:   if (allowed('mcr','/')) {
                   5861:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5862:     foreach my $role (split(':',$sysrole)) {
                   5863: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5864:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5865:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5866: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5867:                return "refused:s:$crole&$cqual"; 
                   5868:             }
                   5869:         }
1.191     harris41 5870:     }
1.800     albertel 5871:     foreach my $role (split(':',$domrole)) {
                   5872: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5873:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5874:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5875: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5876:                return "refused:d:$crole&$cqual"; 
                   5877:             }
                   5878:         }
1.191     harris41 5879:     }
1.800     albertel 5880:     foreach my $role (split(':',$courole)) {
                   5881: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5882:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5883:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5884: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5885:                return "refused:c:$crole&$cqual"; 
                   5886:             }
                   5887:         }
1.191     harris41 5888:     }
1.620     albertel 5889:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5890:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5891: 	        "rolesdef_$rolename=".
                   5892:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5893:     return reply($command,$env{'user.home'});
1.12      www      5894:   } else {
                   5895:     return 'refused';
                   5896:   }
1.105     harris41 5897: }
                   5898: 
                   5899: # ---------------- Make a metadata query against the network of library servers
                   5900: 
                   5901: sub metadata_query {
1.244     matthew  5902:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5903:     my %rhash;
1.845     albertel 5904:     my %libserv = &all_library();
1.244     matthew  5905:     my @server_list = (defined($server_array) ? @$server_array
                   5906:                                               : keys(%libserv) );
                   5907:     for my $server (@server_list) {
1.118     harris41 5908: 	unless ($custom or $customshow) {
                   5909: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5910: 	    $rhash{$server}=$reply;
                   5911: 	}
                   5912: 	else {
                   5913: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5914: 			     &escape($custom).':'.&escape($customshow),
                   5915: 			     $server);
                   5916: 	    $rhash{$server}=$reply;
                   5917: 	}
1.112     harris41 5918:     }
1.118     harris41 5919:     return \%rhash;
1.240     www      5920: }
                   5921: 
                   5922: # ----------------------------------------- Send log queries and wait for reply
                   5923: 
                   5924: sub log_query {
                   5925:     my ($uname,$udom,$query,%filters)=@_;
                   5926:     my $uhome=&homeserver($uname,$udom);
                   5927:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5928:     my $uhost=&hostname($uhome);
1.800     albertel 5929:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5930:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5931:                        $uhome);
1.479     albertel 5932:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5933:     return get_query_reply($queryid);
                   5934: }
                   5935: 
1.818     raeburn  5936: # -------------------------- Update MySQL table for portfolio file
                   5937: 
                   5938: sub update_portfolio_table {
1.821     raeburn  5939:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5940:     if ($group ne '') {
                   5941:         $file_name =~s /^\Q$group\E//;
                   5942:     }
1.818     raeburn  5943:     my $homeserver = &homeserver($uname,$udom);
                   5944:     my $queryid=
1.821     raeburn  5945:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5946:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5947:     my $reply = &get_query_reply($queryid);
                   5948:     return $reply;
                   5949: }
                   5950: 
1.899     raeburn  5951: # -------------------------- Update MySQL allusers table
                   5952: 
                   5953: sub update_allusers_table {
                   5954:     my ($uname,$udom,$names) = @_;
                   5955:     my $homeserver = &homeserver($uname,$udom);
                   5956:     my $queryid=
                   5957:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5958:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5959:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5960:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5961:                'generation='.&escape($names->{'generation'}).'%%'.
                   5962:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5963:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  5964:     return;
1.899     raeburn  5965: }
                   5966: 
1.508     raeburn  5967: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5968: 
                   5969: sub fetch_enrollment_query {
1.511     raeburn  5970:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5971:     my $homeserver;
1.547     raeburn  5972:     my $maxtries = 1;
1.508     raeburn  5973:     if ($context eq 'automated') {
                   5974:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5975:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5976:     } else {
                   5977:         $homeserver = &homeserver($cnum,$dom);
                   5978:     }
1.838     albertel 5979:     my $host=&hostname($homeserver);
1.506     raeburn  5980:     my $cmd = '';
1.1000    raeburn  5981:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5982:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5983:     }
                   5984:     $cmd =~ s/%%$//;
                   5985:     $cmd = &escape($cmd);
                   5986:     my $query = 'fetchenrollment';
1.620     albertel 5987:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5988:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5989:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5990:         return 'error: '.$queryid;
                   5991:     }
1.506     raeburn  5992:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5993:     my $tries = 1;
                   5994:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5995:         $reply = &get_query_reply($queryid);
                   5996:         $tries ++;
                   5997:     }
1.526     raeburn  5998:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5999:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6000:     } else {
1.901     albertel 6001:         my @responses = split(/:/,$reply);
1.515     raeburn  6002:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6003:             foreach my $line (@responses) {
                   6004:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6005:                 $$replyref{$key} = $value;
                   6006:             }
                   6007:         } else {
1.506     raeburn  6008:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 6009:             foreach my $line (@responses) {
                   6010:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6011:                 $$replyref{$key} = $value;
                   6012:                 if ($value > 0) {
1.800     albertel 6013:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6014:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6015:                         my $destname = $pathname.'/'.$filename;
                   6016:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6017:                         if ($xml_classlist =~ /^error/) {
                   6018:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6019:                         } else {
1.506     raeburn  6020:                             if ( open(FILE,">$destname") ) {
                   6021:                                 print FILE &unescape($xml_classlist);
                   6022:                                 close(FILE);
1.526     raeburn  6023:                             } else {
                   6024:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6025:                             }
                   6026:                         }
                   6027:                     }
                   6028:                 }
                   6029:             }
                   6030:         }
                   6031:         return 'ok';
                   6032:     }
                   6033:     return 'error';
                   6034: }
                   6035: 
1.242     www      6036: sub get_query_reply {
                   6037:     my $queryid=shift;
1.240     www      6038:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6039:     my $reply='';
                   6040:     for (1..100) {
                   6041: 	sleep 2;
                   6042:         if (-e $replyfile.'.end') {
1.448     albertel 6043: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6044: 		$reply = join('',<$fh>);
                   6045: 		close($fh);
1.240     www      6046: 	   } else { return 'error: reply_file_error'; }
1.242     www      6047:            return &unescape($reply);
                   6048: 	}
1.240     www      6049:     }
1.242     www      6050:     return 'timeout:'.$queryid;
1.240     www      6051: }
                   6052: 
                   6053: sub courselog_query {
1.241     www      6054: #
                   6055: # possible filters:
                   6056: # url: url or symb
                   6057: # username
                   6058: # domain
                   6059: # action: view, submit, grade
                   6060: # start: timestamp
                   6061: # end: timestamp
                   6062: #
1.240     www      6063:     my (%filters)=@_;
1.620     albertel 6064:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6065:     if ($filters{'url'}) {
                   6066: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6067:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6068:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6069:     }
1.620     albertel 6070:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6071:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6072:     return &log_query($cname,$cdom,'courselog',%filters);
                   6073: }
                   6074: 
                   6075: sub userlog_query {
1.858     raeburn  6076: #
                   6077: # possible filters:
                   6078: # action: log check role
                   6079: # start: timestamp
                   6080: # end: timestamp
                   6081: #
1.240     www      6082:     my ($uname,$udom,%filters)=@_;
                   6083:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6084: }
                   6085: 
1.506     raeburn  6086: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6087: 
                   6088: sub auto_run {
1.508     raeburn  6089:     my ($cnum,$cdom) = @_;
1.876     raeburn  6090:     my $response = 0;
                   6091:     my $settings;
                   6092:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6093:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6094:         $settings = $domconfig{'autoenroll'};
                   6095:         if ($settings->{'run'} eq '1') {
                   6096:             $response = 1;
                   6097:         }
                   6098:     } else {
1.934     raeburn  6099:         my $homeserver;
                   6100:         if (&is_course($cdom,$cnum)) {
                   6101:             $homeserver = &homeserver($cnum,$cdom);
                   6102:         } else {
                   6103:             $homeserver = &domain($cdom,'primary');
                   6104:         }
                   6105:         if ($homeserver ne 'no_host') {
                   6106:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6107:         }
1.876     raeburn  6108:     }
1.506     raeburn  6109:     return $response;
                   6110: }
1.776     albertel 6111: 
1.506     raeburn  6112: sub auto_get_sections {
1.508     raeburn  6113:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6114:     my $homeserver;
                   6115:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6116:         $homeserver = &homeserver($cnum,$cdom);
                   6117:     }
                   6118:     if (!defined($homeserver)) { 
                   6119:         if ($cdom =~ /^$match_domain$/) {
                   6120:             $homeserver = &domain($cdom,'primary');
                   6121:         }
                   6122:     }
                   6123:     my @secs;
                   6124:     if (defined($homeserver)) {
                   6125:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6126:         unless ($response eq 'refused') {
                   6127:             @secs = split(/:/,$response);
                   6128:         }
1.506     raeburn  6129:     }
                   6130:     return @secs;
                   6131: }
1.776     albertel 6132: 
1.506     raeburn  6133: sub auto_new_course {
1.1056.4.19  raeburn  6134:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6135:     my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19  raeburn  6136:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6137:     return $response;
                   6138: }
1.776     albertel 6139: 
1.506     raeburn  6140: sub auto_validate_courseID {
1.508     raeburn  6141:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6142:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6143:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6144:     return $response;
                   6145: }
1.776     albertel 6146: 
1.1007    raeburn  6147: sub auto_validate_instcode {
1.1020    raeburn  6148:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6149:     my ($homeserver,$response);
                   6150:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6151:         $homeserver = &homeserver($cnum,$cdom);
                   6152:     }
                   6153:     if (!defined($homeserver)) {
                   6154:         if ($cdom =~ /^$match_domain$/) {
                   6155:             $homeserver = &domain($cdom,'primary');
                   6156:         }
                   6157:     }
1.1056.4.2  raeburn  6158:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6159:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6160:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6161:     return ($outcome,$description);
1.1007    raeburn  6162: }
                   6163: 
1.506     raeburn  6164: sub auto_create_password {
1.873     raeburn  6165:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6166:     my ($homeserver,$response);
1.506     raeburn  6167:     my $create_passwd = 0;
                   6168:     my $authchk = '';
1.873     raeburn  6169:     if ($udom =~ /^$match_domain$/) {
                   6170:         $homeserver = &domain($udom,'primary');
                   6171:     }
                   6172:     if ($homeserver eq '') {
                   6173:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6174:             $homeserver = &homeserver($cnum,$cdom);
                   6175:         }
                   6176:     }
                   6177:     if ($homeserver eq '') {
                   6178:         $authchk = 'nodomain';
1.506     raeburn  6179:     } else {
1.873     raeburn  6180:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6181:         if ($response eq 'refused') {
                   6182:             $authchk = 'refused';
                   6183:         } else {
1.901     albertel 6184:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6185:         }
1.506     raeburn  6186:     }
                   6187:     return ($authparam,$create_passwd,$authchk);
                   6188: }
                   6189: 
1.706     raeburn  6190: sub auto_photo_permission {
                   6191:     my ($cnum,$cdom,$students) = @_;
                   6192:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6193:     my ($outcome,$perm_reqd,$conditions) = 
                   6194: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6195:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6196: 	return (undef,undef);
                   6197:     }
1.706     raeburn  6198:     return ($outcome,$perm_reqd,$conditions);
                   6199: }
                   6200: 
                   6201: sub auto_checkphotos {
                   6202:     my ($uname,$udom,$pid) = @_;
                   6203:     my $homeserver = &homeserver($uname,$udom);
                   6204:     my ($result,$resulttype);
                   6205:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6206: 				   &escape($uname).':'.&escape($pid),
                   6207: 				   $homeserver));
1.709     albertel 6208:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6209: 	return (undef,undef);
                   6210:     }
1.706     raeburn  6211:     if ($outcome) {
                   6212:         ($result,$resulttype) = split(/:/,$outcome);
                   6213:     } 
                   6214:     return ($result,$resulttype);
                   6215: }
                   6216: 
                   6217: sub auto_photochoice {
                   6218:     my ($cnum,$cdom) = @_;
                   6219:     my $homeserver = &homeserver($cnum,$cdom);
                   6220:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6221: 						       &escape($cdom),
                   6222: 						       $homeserver)));
1.709     albertel 6223:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6224: 	return (undef,undef);
                   6225:     }
1.706     raeburn  6226:     return ($update,$comment);
                   6227: }
                   6228: 
                   6229: sub auto_photoupdate {
                   6230:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6231:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6232:     my $host=&hostname($homeserver);
1.706     raeburn  6233:     my $cmd = '';
                   6234:     my $maxtries = 1;
1.800     albertel 6235:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6236:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6237:     }
                   6238:     $cmd =~ s/%%$//;
                   6239:     $cmd = &escape($cmd);
                   6240:     my $query = 'institutionalphotos';
                   6241:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6242:     unless ($queryid=~/^\Q$host\E\_/) {
                   6243:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6244:         return 'error: '.$queryid;
                   6245:     }
                   6246:     my $reply = &get_query_reply($queryid);
                   6247:     my $tries = 1;
                   6248:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6249:         $reply = &get_query_reply($queryid);
                   6250:         $tries ++;
                   6251:     }
                   6252:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6253:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6254:     } else {
                   6255:         my @responses = split(/:/,$reply);
                   6256:         my $outcome = shift(@responses); 
                   6257:         foreach my $item (@responses) {
                   6258:             my ($key,$value) = split(/=/,$item);
                   6259:             $$photo{$key} = $value;
                   6260:         }
                   6261:         return $outcome;
                   6262:     }
                   6263:     return 'error';
                   6264: }
                   6265: 
1.521     raeburn  6266: sub auto_instcode_format {
1.793     albertel 6267:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6268: 	$cat_order) = @_;
1.521     raeburn  6269:     my $courses = '';
1.772     raeburn  6270:     my @homeservers;
1.521     raeburn  6271:     if ($caller eq 'global') {
1.841     albertel 6272: 	my %servers = &get_servers($codedom,'library');
                   6273: 	foreach my $tryserver (keys(%servers)) {
                   6274: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6275: 		push(@homeservers,$tryserver);
                   6276: 	    }
1.584     raeburn  6277:         }
1.1022    raeburn  6278:     } elsif ($caller eq 'requests') {
                   6279:         if ($codedom =~ /^$match_domain$/) {
                   6280:             my $chome = &domain($codedom,'primary');
                   6281:             unless ($chome eq 'no_host') {
                   6282:                 push(@homeservers,$chome);
                   6283:             }
                   6284:         }
1.521     raeburn  6285:     } else {
1.772     raeburn  6286:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6287:     }
1.793     albertel 6288:     foreach my $code (keys(%{$instcodes})) {
                   6289:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6290:     }
                   6291:     chop($courses);
1.772     raeburn  6292:     my $ok_response = 0;
                   6293:     my $response;
                   6294:     while (@homeservers > 0 && $ok_response == 0) {
                   6295:         my $server = shift(@homeservers); 
                   6296:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6297:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6298:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6299: 		split(/:/,$response);
1.772     raeburn  6300:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6301:             push(@{$codetitles},&str2array($codetitles_str));
                   6302:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6303:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6304:             $ok_response = 1;
                   6305:         }
                   6306:     }
                   6307:     if ($ok_response) {
1.521     raeburn  6308:         return 'ok';
1.772     raeburn  6309:     } else {
                   6310:         return $response;
1.521     raeburn  6311:     }
                   6312: }
                   6313: 
1.792     raeburn  6314: sub auto_instcode_defaults {
                   6315:     my ($domain,$returnhash,$code_order) = @_;
                   6316:     my @homeservers;
1.841     albertel 6317: 
                   6318:     my %servers = &get_servers($domain,'library');
                   6319:     foreach my $tryserver (keys(%servers)) {
                   6320: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6321: 	    push(@homeservers,$tryserver);
                   6322: 	}
1.792     raeburn  6323:     }
1.841     albertel 6324: 
1.792     raeburn  6325:     my $response;
1.841     albertel 6326:     foreach my $server (@homeservers) {
1.792     raeburn  6327:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6328:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6329: 	
                   6330: 	foreach my $pair (split(/\&/,$response)) {
                   6331: 	    my ($name,$value)=split(/\=/,$pair);
                   6332: 	    if ($name eq 'code_order') {
                   6333: 		@{$code_order} = split(/\&/,&unescape($value));
                   6334: 	    } else {
                   6335: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6336: 	    }
                   6337: 	}
                   6338: 	return 'ok';
1.792     raeburn  6339:     }
1.841     albertel 6340: 
                   6341:     return $response;
1.1003    raeburn  6342: }
                   6343: 
                   6344: sub auto_possible_instcodes {
1.1007    raeburn  6345:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6346:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6347:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6348:         return;
                   6349:     }
1.1003    raeburn  6350:     my (@homeservers,$uhome);
                   6351:     if (defined(&domain($domain,'primary'))) {
                   6352:         $uhome=&domain($domain,'primary');
                   6353:         push(@homeservers,&domain($domain,'primary'));
                   6354:     } else {
                   6355:         my %servers = &get_servers($domain,'library');
                   6356:         foreach my $tryserver (keys(%servers)) {
                   6357:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6358:                 push(@homeservers,$tryserver);
                   6359:             }
                   6360:         }
                   6361:     }
                   6362:     my $response;
                   6363:     foreach my $server (@homeservers) {
                   6364:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6365:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6366:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6367:             split(':',$response);
                   6368:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6369:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6370:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6371:             my ($name,$value)=split('=',$item);
                   6372:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6373:         }
                   6374:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6375:             my ($name,$value)=split('=',$item);
                   6376:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6377:         }
                   6378:         return 'ok';
                   6379:     }
                   6380:     return $response;
                   6381: }
1.792     raeburn  6382: 
1.1010    raeburn  6383: sub auto_courserequest_checks {
                   6384:     my ($dom) = @_;
1.1020    raeburn  6385:     my ($homeserver,%validations);
                   6386:     if ($dom =~ /^$match_domain$/) {
                   6387:         $homeserver = &domain($dom,'primary');
                   6388:     }
                   6389:     unless ($homeserver eq 'no_host') {
                   6390:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6391:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6392:             my @items = split(/&/,$response);
                   6393:             foreach my $item (@items) {
                   6394:                 my ($key,$value) = split('=',$item);
                   6395:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6396:             }
                   6397:         }
                   6398:     }
1.1010    raeburn  6399:     return %validations; 
                   6400: }
                   6401: 
1.1020    raeburn  6402: sub auto_courserequest_validation {
                   6403:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6404:     my ($homeserver,$response);
                   6405:     if ($dom =~ /^$match_domain$/) {
                   6406:         $homeserver = &domain($dom,'primary');
                   6407:     }
                   6408:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6409:           
1.1020    raeburn  6410:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6411:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6412:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6413:                                     $homeserver));
                   6414:     }
                   6415:     return $response;
                   6416: }
                   6417: 
1.777     albertel 6418: sub auto_validate_class_sec {
1.918     raeburn  6419:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6420:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6421:     my $ownerlist;
                   6422:     if (ref($owners) eq 'ARRAY') {
                   6423:         $ownerlist = join(',',@{$owners});
                   6424:     } else {
                   6425:         $ownerlist = $owners;
                   6426:     }
1.773     raeburn  6427:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6428:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6429:     return $response;
                   6430: }
                   6431: 
1.679     raeburn  6432: # ------------------------------------------------------- Course Group routines
                   6433: 
                   6434: sub get_coursegroups {
1.809     raeburn  6435:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6436:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6437: }
                   6438: 
1.679     raeburn  6439: sub modify_coursegroup {
                   6440:     my ($cdom,$cnum,$groupsettings) = @_;
                   6441:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6442: }
                   6443: 
1.809     raeburn  6444: sub toggle_coursegroup_status {
                   6445:     my ($cdom,$cnum,$group,$action) = @_;
                   6446:     my ($from_namespace,$to_namespace);
                   6447:     if ($action eq 'delete') {
                   6448:         $from_namespace = 'coursegroups';
                   6449:         $to_namespace = 'deleted_groups';
                   6450:     } else {
                   6451:         $from_namespace = 'deleted_groups';
                   6452:         $to_namespace = 'coursegroups';
                   6453:     }
                   6454:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6455:     if (my $tmp = &error(%curr_group)) {
                   6456:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6457:         return ('read error',$tmp);
                   6458:     } else {
                   6459:         my %savedsettings = %curr_group; 
1.809     raeburn  6460:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6461:         my $deloutcome;
                   6462:         if ($result eq 'ok') {
1.809     raeburn  6463:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6464:         } else {
                   6465:             return ('write error',$result);
                   6466:         }
                   6467:         if ($deloutcome eq 'ok') {
                   6468:             return 'ok';
                   6469:         } else {
                   6470:             return ('delete error',$deloutcome);
                   6471:         }
                   6472:     }
                   6473: }
                   6474: 
1.679     raeburn  6475: sub modify_group_roles {
1.957     raeburn  6476:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6477:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6478:     my $role = 'gr/'.&escape($userprivs);
                   6479:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6480:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6481:     if ($result eq 'ok') {
                   6482:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6483:     }
1.679     raeburn  6484:     return $result;
                   6485: }
                   6486: 
                   6487: sub modify_coursegroup_membership {
                   6488:     my ($cdom,$cnum,$membership) = @_;
                   6489:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6490:     return $result;
                   6491: }
                   6492: 
1.682     raeburn  6493: sub get_active_groups {
                   6494:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6495:     my $now = time;
                   6496:     my %groups = ();
                   6497:     foreach my $key (keys(%env)) {
1.811     albertel 6498:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6499:             my ($start,$end) = split(/\./,$env{$key});
                   6500:             if (($end!=0) && ($end<$now)) { next; }
                   6501:             if (($start!=0) && ($start>$now)) { next; }
                   6502:             if ($1 eq $cdom && $2 eq $cnum) {
                   6503:                 $groups{$3} = $env{$key} ;
                   6504:             }
                   6505:         }
                   6506:     }
                   6507:     return %groups;
                   6508: }
                   6509: 
1.683     raeburn  6510: sub get_group_membership {
                   6511:     my ($cdom,$cnum,$group) = @_;
                   6512:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6513: }
                   6514: 
                   6515: sub get_users_groups {
                   6516:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6517:     my @usersgroups;
1.683     raeburn  6518:     my $cachetime=1800;
                   6519: 
                   6520:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6521:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6522:     if (defined($cached)) {
1.734     albertel 6523:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6524:     } else {  
                   6525:         $grouplist = '';
1.816     raeburn  6526:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6527:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6528:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6529:         my $access_end = $env{'course.'.$courseid.
                   6530:                               '.default_enrollment_end_date'};
                   6531:         my $now = time;
                   6532:         foreach my $key (keys(%roleshash)) {
                   6533:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6534:                 my $group = $1;
                   6535:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6536:                     my $start = $2;
                   6537:                     my $end = $1;
                   6538:                     if ($start == -1) { next; } # deleted from group
                   6539:                     if (($start!=0) && ($start>$now)) { next; }
                   6540:                     if (($end!=0) && ($end<$now)) {
                   6541:                         if ($access_end && $access_end < $now) {
                   6542:                             if ($access_end - $end < 86400) {
                   6543:                                 push(@usersgroups,$group);
1.733     raeburn  6544:                             }
                   6545:                         }
1.817     raeburn  6546:                         next;
1.733     raeburn  6547:                     }
1.817     raeburn  6548:                     push(@usersgroups,$group);
1.683     raeburn  6549:                 }
                   6550:             }
                   6551:         }
1.817     raeburn  6552:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6553:         $grouplist = join(':',@usersgroups);
                   6554:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6555:     }
1.733     raeburn  6556:     return @usersgroups;
1.683     raeburn  6557: }
                   6558: 
                   6559: sub devalidate_getgroups_cache {
                   6560:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6561:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6562: 
1.683     raeburn  6563:     my $hashid="$udom:$uname:$courseid";
                   6564:     &devalidate_cache_new('getgroups',$hashid);
                   6565: }
                   6566: 
1.12      www      6567: # ------------------------------------------------------------------ Plain Text
                   6568: 
                   6569: sub plaintext {
1.988     raeburn  6570:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6571:     if ($short =~ m{^cr/}) {
1.758     albertel 6572: 	return (split('/',$short))[-1];
                   6573:     }
1.742     raeburn  6574:     if (!defined($cid)) {
                   6575:         $cid = $env{'request.course.id'};
                   6576:     }
                   6577:     my %rolenames = (
1.1008    raeburn  6578:                       Course    => 'std',
                   6579:                       Community => 'alt1',
1.742     raeburn  6580:                     );
1.1037    raeburn  6581:     if ($cid ne '') {
                   6582:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6583:             unless ($forcedefault) {
                   6584:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6585:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6586:                 return &Apache::lonlocal::mt($roletext);
                   6587:             }
                   6588:         }
                   6589:     }
                   6590:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6591:         (defined($rolenames{$type})) && 
                   6592:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6593:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6594:     } elsif ($cid ne '') {
                   6595:         my $crstype = $env{'course.'.$cid.'.type'};
                   6596:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6597:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6598:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6599:         }
1.742     raeburn  6600:     }
1.1037    raeburn  6601:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6602: }
                   6603: 
                   6604: # ----------------------------------------------------------------- Assign Role
                   6605: 
                   6606: sub assignrole {
1.957     raeburn  6607:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6608:         $context)=@_;
1.21      www      6609:     my $mrole;
                   6610:     if ($role =~ /^cr\//) {
1.393     www      6611:         my $cwosec=$url;
1.811     albertel 6612:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6613: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6614:            my $refused = 1;
                   6615:            if ($context eq 'requestcourses') {
                   6616:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6617:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6618:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6619:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6620:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6621:                            if ($crsenv{'internal.courseowner'} eq
                   6622:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6623:                                $refused = '';
                   6624:                            }
                   6625:                        }
                   6626:                    }
                   6627:                }
                   6628:            }
                   6629:            if ($refused) {
                   6630:                &logthis('Refused custom assignrole: '.
                   6631:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6632:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6633:                return 'refused';
                   6634:            }
1.104     www      6635:         }
1.21      www      6636:         $mrole='cr';
1.678     raeburn  6637:     } elsif ($role =~ /^gr\//) {
                   6638:         my $cwogrp=$url;
1.811     albertel 6639:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6640:         unless (&allowed('mdg',$cwogrp)) {
                   6641:             &logthis('Refused group assignrole: '.
                   6642:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6643:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6644:             return 'refused';
                   6645:         }
                   6646:         $mrole='gr';
1.21      www      6647:     } else {
1.82      www      6648:         my $cwosec=$url;
1.811     albertel 6649:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6650:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6651:             my $refused;
                   6652:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6653:                 if (!(&allowed('c'.$role,$url))) {
                   6654:                     $refused = 1;
                   6655:                 }
                   6656:             } else {
                   6657:                 $refused = 1;
                   6658:             }
1.947     raeburn  6659:             if ($refused) {
1.1045    raeburn  6660:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6661:                 if (!$selfenroll && $context eq 'course') {
                   6662:                     my %crsenv;
                   6663:                     if ($role eq 'cc' || $role eq 'co') {
                   6664:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6665:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6666:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6667:                                 if ($crsenv{'internal.courseowner'} eq 
                   6668:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6669:                                     $refused = '';
                   6670:                                 }
                   6671:                             }
                   6672:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6673:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6674:                                 if ($crsenv{'internal.courseowner'} eq 
                   6675:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6676:                                     $refused = '';
                   6677:                                 }
                   6678:                             }
                   6679:                         }
                   6680:                     }
                   6681:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6682:                     $refused = '';
1.1017    raeburn  6683:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6684:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6685:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6686:                         my $wrongcc;
                   6687:                         if ($cnum =~ /^$match_community$/) {
                   6688:                             $wrongcc = 1 if ($role eq 'cc');
                   6689:                         } else {
                   6690:                             $wrongcc = 1 if ($role eq 'co');
                   6691:                         }
                   6692:                         unless ($wrongcc) {
                   6693:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6694:                             if ($crsenv{'internal.courseowner'} eq 
                   6695:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6696:                                 $refused = '';
                   6697:                             }
1.1017    raeburn  6698:                         }
                   6699:                     }
                   6700:                 }
                   6701:                 if ($refused) {
1.947     raeburn  6702:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6703:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6704: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6705:                     return 'refused';
                   6706:                 }
1.932     raeburn  6707:             }
1.104     www      6708:         }
1.21      www      6709:         $mrole=$role;
                   6710:     }
1.620     albertel 6711:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6712:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6713:     if ($end) { $command.='_'.$end; }
1.21      www      6714:     if ($start) {
                   6715: 	if ($end) { 
1.81      www      6716:            $command.='_'.$start; 
1.21      www      6717:         } else {
1.81      www      6718:            $command.='_0_'.$start;
1.21      www      6719:         }
                   6720:     }
1.739     raeburn  6721:     my $origstart = $start;
                   6722:     my $origend = $end;
1.957     raeburn  6723:     my $delflag;
1.357     www      6724: # actually delete
                   6725:     if ($deleteflag) {
1.373     www      6726: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6727: # modify command to delete the role
1.620     albertel 6728:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6729:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6730: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6731: # set start and finish to negative values for userrolelog
                   6732:            $start=-1;
                   6733:            $end=-1;
1.957     raeburn  6734:            $delflag = 1;
1.357     www      6735:         }
                   6736:     }
                   6737: # send command
1.349     www      6738:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6739: # log new user role if status is ok
1.349     www      6740:     if ($answer eq 'ok') {
1.663     raeburn  6741: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6742: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6743:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6744:         unless ($role =~ /^gr/) {
                   6745:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6746:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6747:         }
1.1053    raeburn  6748:         if ($role eq 'cc') {
                   6749:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6750:         }
1.349     www      6751:     }
                   6752:     return $answer;
1.169     harris41 6753: }
                   6754: 
1.1053    raeburn  6755: sub autoupdate_coowners {
                   6756:     my ($url,$end,$start,$uname,$udom) = @_;
                   6757:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6758:     if (($cdom ne '') && ($cnum ne '')) {
                   6759:         my $now = time;
                   6760:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6761:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6762:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6763:             my $instcode = $coursehash{'internal.coursecode'};
                   6764:             if ($instcode ne '') {
1.1056    raeburn  6765:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6766:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6767:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6768:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6769:                         if ($result eq 'valid') {
                   6770:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6771:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6772:                                     push(@newcoowners,$coowner);
                   6773:                                 }
                   6774:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6775:                                     push(@newcoowners,$uname.':'.$udom);
                   6776:                                 }
                   6777:                                 @newcoowners = sort(@newcoowners);
                   6778:                             } else {
                   6779:                                 push(@newcoowners,$uname.':'.$udom);
                   6780:                             }
                   6781:                         } else {
                   6782:                             if ($coursehash{'internal.co-owners'}) {
                   6783:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6784:                                     unless ($coowner eq $uname.':'.$udom) {
                   6785:                                         push(@newcoowners,$coowner);
                   6786:                                     }
                   6787:                                 }
                   6788:                                 unless (@newcoowners > 0) {
                   6789:                                     $delcoowners = 1;
                   6790:                                     $coowners = '';
                   6791:                                 }
                   6792:                             }
                   6793:                         }
                   6794:                         if (@newcoowners || $delcoowners) {
                   6795:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6796:                                             $delcoowners,@newcoowners);
                   6797:                         }
                   6798:                     }
                   6799:                 }
                   6800:             }
                   6801:         }
                   6802:     }
                   6803: }
                   6804: 
                   6805: sub store_coowners {
                   6806:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6807:     my $cid = $cdom.'_'.$cnum;
                   6808:     my ($coowners,$delresult,$putresult);
                   6809:     if (@newcoowners) {
                   6810:         $coowners = join(',',@newcoowners);
                   6811:         my %coownershash = (
                   6812:                             'internal.co-owners' => $coowners,
                   6813:                            );
                   6814:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6815:         if ($putresult eq 'ok') {
                   6816:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6817:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6818:             }
                   6819:         }
                   6820:     }
                   6821:     if ($delcoowners) {
                   6822:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6823:         if ($delresult eq 'ok') {
                   6824:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6825:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6826:             }
                   6827:         }
                   6828:     }
                   6829:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6830:         my %crsinfo =
                   6831:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6832:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6833:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6834:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6835:         }
                   6836:     }
                   6837: }
                   6838: 
1.169     harris41 6839: # -------------------------------------------------- Modify user authentication
1.197     www      6840: # Overrides without validation
                   6841: 
1.169     harris41 6842: sub modifyuserauth {
                   6843:     my ($udom,$uname,$umode,$upass)=@_;
                   6844:     my $uhome=&homeserver($uname,$udom);
1.197     www      6845:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6846:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6847:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6848:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6849:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6850: 		     &escape($upass),$uhome);
1.620     albertel 6851:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6852:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6853:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6854:     &log($udom,,$uname,$uhome,
1.620     albertel 6855:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6856:                                      $env{'user.name'}.', '.$umode.
1.197     www      6857:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6858:     unless ($reply eq 'ok') {
1.197     www      6859:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6860: 	return 'error: '.$reply;
                   6861:     }   
1.170     harris41 6862:     return 'ok';
1.80      www      6863: }
                   6864: 
1.81      www      6865: # --------------------------------------------------------------- Modify a user
1.80      www      6866: 
1.81      www      6867: sub modifyuser {
1.206     matthew  6868:     my ($udom,    $uname, $uid,
                   6869:         $umode,   $upass, $first,
                   6870:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6871:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6872:     $udom= &LONCAPA::clean_domain($udom);
                   6873:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6874:     my $showcandelete = 'none';
                   6875:     if (ref($candelete) eq 'ARRAY') {
                   6876:         if (@{$candelete} > 0) {
                   6877:             $showcandelete = join(', ',@{$candelete});
                   6878:         }
                   6879:     }
1.81      www      6880:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6881:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6882:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6883:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6884:                                      ' desiredhome not specified'). 
1.620     albertel 6885:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6886:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6887:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6888:     my $newuser;
                   6889:     if ($uhome eq 'no_host') {
                   6890:         $newuser = 1;
                   6891:     }
1.80      www      6892: # ----------------------------------------------------------------- Create User
1.406     albertel 6893:     if (($uhome eq 'no_host') && 
                   6894: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6895:         my $unhome='';
1.844     albertel 6896:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6897:             $unhome = $desiredhome;
1.620     albertel 6898: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6899: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6900:         } else { # load balancing routine for determining $unhome
1.81      www      6901:             my $loadm=10000000;
1.841     albertel 6902: 	    my %servers = &get_servers($udom,'library');
                   6903: 	    foreach my $tryserver (keys(%servers)) {
                   6904: 		my $answer=reply('load',$tryserver);
                   6905: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6906: 		    $loadm=$answer;
                   6907: 		    $unhome=$tryserver;
                   6908: 		}
1.80      www      6909: 	    }
                   6910:         }
                   6911:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6912: 	    return 'error: unable to find a home server for '.$uname.
                   6913:                    ' in domain '.$udom;
1.80      www      6914:         }
                   6915:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6916:                          &escape($upass),$unhome);
                   6917: 	unless ($reply eq 'ok') {
                   6918:             return 'error: '.$reply;
                   6919:         }   
1.230     stredwic 6920:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6921:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6922: 	    return 'error: unable verify users home machine.';
1.80      www      6923:         }
1.209     matthew  6924:     }   # End of creation of new user
1.80      www      6925: # ---------------------------------------------------------------------- Add ID
                   6926:     if ($uid) {
                   6927:        $uid=~tr/A-Z/a-z/;
                   6928:        my %uidhash=&idrget($udom,$uname);
1.196     www      6929:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6930:          && (!$forceid)) {
1.80      www      6931: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6932: 	      return 'error: user id "'.$uid.'" does not match '.
                   6933:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6934:           }
                   6935:        } else {
                   6936: 	  &idput($udom,($uname => $uid));
                   6937:        }
                   6938:     }
                   6939: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6940:     my @tmp=&get('environment',
1.899     raeburn  6941: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6942:                     'permanentemail','inststatus'],
1.134     albertel 6943: 		   $udom,$uname);
1.1056.4.4  raeburn  6944:     my (%names,%oldnames);
1.313     matthew  6945:     if ($tmp[0] =~ m/^error:.*/) { 
                   6946:         %names=(); 
                   6947:     } else {
                   6948:         %names = @tmp;
1.1056.4.4  raeburn  6949:         %oldnames = %names;
1.313     matthew  6950:     }
1.1056.4.6  raeburn  6951: #
1.1056.4.1  raeburn  6952: # If name, email and/or uid are blank (e.g., because an uploaded file
                   6953: # of users did not contain them), do not overwrite existing values
                   6954: # unless field is in $candelete array ref.  
                   6955: #
                   6956: 
                   6957:     my @fields = ('firstname','middlename','lastname','generation',
                   6958:                   'permanentemail','id');
                   6959:     my %newvalues;
                   6960:     if (ref($candelete) eq 'ARRAY') {
                   6961:         foreach my $field (@fields) {
                   6962:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   6963:                 if ($field eq 'firstname') {
                   6964:                     $names{$field} = $first;
                   6965:                 } elsif ($field eq 'middlename') {
                   6966:                     $names{$field} = $middle;
                   6967:                 } elsif ($field eq 'lastname') {
                   6968:                     $names{$field} = $last;
                   6969:                 } elsif ($field eq 'generation') { 
                   6970:                     $names{$field} = $gene;
                   6971:                 } elsif ($field eq 'permanentemail') {
                   6972:                     $names{$field} = $email;
                   6973:                 } elsif ($field eq 'id') {
                   6974:                     $names{$field}  = $uid;
                   6975:                 }
                   6976:             }
                   6977:         }
                   6978:     }
1.388     www      6979:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6980:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6981:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6982:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6983:     if ($email) {
                   6984:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6985:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6986:     }
1.899     raeburn  6987:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6988:     if (defined($inststatus)) {
                   6989:         $names{'inststatus'} = '';
                   6990:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6991:         if (ref($usertypes) eq 'HASH') {
                   6992:             my @okstatuses; 
                   6993:             foreach my $item (split(/:/,$inststatus)) {
                   6994:                 if (defined($usertypes->{$item})) {
                   6995:                     push(@okstatuses,$item);  
                   6996:                 }
                   6997:             }
                   6998:             if (@okstatuses) {
                   6999:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7000:             }
                   7001:         }
                   7002:     }
1.1056.4.4  raeburn  7003:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7004:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  7005:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7006:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7007:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7008:     } else {
                   7009:         $logmsg .= ' during self creation';
                   7010:     }
1.1056.4.4  raeburn  7011:     my $changed;
                   7012:     if ($newuser) {
                   7013:         $changed = 1;
                   7014:     } else {
                   7015:         foreach my $field (@fields) {
                   7016:             if ($names{$field} ne $oldnames{$field}) {
                   7017:                 $changed = 1;
                   7018:                 last;
                   7019:             }
                   7020:         }
                   7021:     }
                   7022:     unless ($changed) {
                   7023:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7024:         &logthis($logmsg);
                   7025:         return 'ok';
                   7026:     }
                   7027:     my $reply = &put('environment', \%names, $udom,$uname);
                   7028:     if ($reply ne 'ok') {
                   7029:         return 'error: '.$reply;
                   7030:     }
1.1056.4.11  raeburn  7031:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7032:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7033:     }
1.1056.4.4  raeburn  7034:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7035:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7036:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7037:     &logthis($logmsg);
1.134     albertel 7038:     return 'ok';
1.80      www      7039: }
                   7040: 
1.81      www      7041: # -------------------------------------------------------------- Modify student
1.80      www      7042: 
1.81      www      7043: sub modifystudent {
                   7044:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7045:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7046:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7047:     if (!$cid) {
1.620     albertel 7048: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7049: 	    return 'not_in_class';
                   7050: 	}
1.80      www      7051:     }
                   7052: # --------------------------------------------------------------- Make the user
1.81      www      7053:     my $reply=&modifyuser
1.209     matthew  7054: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7055:          $desiredhome,$email,$inststatus);
1.80      www      7056:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7057:     # This will cause &modify_student_enrollment to get the uid from the
                   7058:     # students environment
                   7059:     $uid = undef if (!$forceid);
1.455     albertel 7060:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7061: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7062:     return $reply;
                   7063: }
                   7064: 
                   7065: sub modify_student_enrollment {
1.957     raeburn  7066:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7067:     my ($cdom,$cnum,$chome);
                   7068:     if (!$cid) {
1.620     albertel 7069: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7070: 	    return 'not_in_class';
                   7071: 	}
1.620     albertel 7072: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7073: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7074:     } else {
                   7075: 	($cdom,$cnum)=split(/_/,$cid);
                   7076:     }
1.620     albertel 7077:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7078:     if (!$chome) {
1.457     raeburn  7079: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7080:     }
1.455     albertel 7081:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7082:     # Make sure the user exists
1.81      www      7083:     my $uhome=&homeserver($uname,$udom);
                   7084:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7085: 	return 'error: no such user';
                   7086:     }
1.297     matthew  7087:     # Get student data if we were not given enough information
                   7088:     if (!defined($first)  || $first  eq '' || 
                   7089:         !defined($last)   || $last   eq '' || 
                   7090:         !defined($uid)    || $uid    eq '' || 
                   7091:         !defined($middle) || $middle eq '' || 
                   7092:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7093:         # They did not supply us with enough data to enroll the student, so
                   7094:         # we need to pick up more information.
1.297     matthew  7095:         my %tmp = &get('environment',
1.294     matthew  7096:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7097:                        ,$udom,$uname);
                   7098: 
1.800     albertel 7099:         #foreach my $key (keys(%tmp)) {
                   7100:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7101:         #}
1.294     matthew  7102:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7103:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7104:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7105:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7106:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7107:     }
1.556     albertel 7108:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7109:     my $reply=cput('classlist',
                   7110: 		   {"$uname:$udom" => 
1.515     raeburn  7111: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7112: 		   $cdom,$cnum);
1.81      www      7113:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7114: 	return 'error: '.$reply;
1.652     albertel 7115:     } else {
                   7116: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7117:     }
1.297     matthew  7118:     # Add student role to user
1.83      www      7119:     my $uurl='/'.$cid;
1.81      www      7120:     $uurl=~s/\_/\//g;
                   7121:     if ($usec) {
                   7122: 	$uurl.='/'.$usec;
                   7123:     }
1.957     raeburn  7124:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7125: }
                   7126: 
1.556     albertel 7127: sub format_name {
                   7128:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7129:     my $name;
                   7130:     if ($first ne 'lastname') {
                   7131: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7132:     } else {
                   7133: 	if ($lastname=~/\S/) {
                   7134: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7135: 	    $name=~s/\s+,/,/;
                   7136: 	} else {
                   7137: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7138: 	}
                   7139:     }
                   7140:     $name=~s/^\s+//;
                   7141:     $name=~s/\s+$//;
                   7142:     $name=~s/\s+/ /g;
                   7143:     return $name;
                   7144: }
                   7145: 
1.84      www      7146: # ------------------------------------------------- Write to course preferences
                   7147: 
                   7148: sub writecoursepref {
                   7149:     my ($courseid,%prefs)=@_;
                   7150:     $courseid=~s/^\///;
                   7151:     $courseid=~s/\_/\//g;
                   7152:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7153:     my $chome=homeserver($cnum,$cdomain);
                   7154:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7155: 	return 'error: no such course';
                   7156:     }
                   7157:     my $cstring='';
1.800     albertel 7158:     foreach my $pref (keys(%prefs)) {
                   7159: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7160:     }
1.84      www      7161:     $cstring=~s/\&$//;
                   7162:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7163: }
                   7164: 
                   7165: # ---------------------------------------------------------- Make/modify course
                   7166: 
                   7167: sub createcourse {
1.741     raeburn  7168:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7169:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7170:     $url=&declutter($url);
                   7171:     my $cid='';
1.1028    raeburn  7172:     if ($context eq 'requestcourses') {
                   7173:         my $can_create = 0;
                   7174:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7175:         if ($udom eq $ownerdom) {
                   7176:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7177:                                   $context)) {
                   7178:                 $can_create = 1;
                   7179:             }
                   7180:         } else {
                   7181:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7182:                                            $category);
                   7183:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7184:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7185:                 if (@curr > 0) {
                   7186:                     my @options = qw(approval validate autolimit);
                   7187:                     my $optregex = join('|',@options);
                   7188:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7189:                         $can_create = 1;
                   7190:                     }
                   7191:                 }
                   7192:             }
                   7193:         }
                   7194:         if ($can_create) {
                   7195:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7196:                 unless (&allowed('ccc',$udom)) {
                   7197:                     return 'refused'; 
                   7198:                 }
1.1017    raeburn  7199:             }
                   7200:         } else {
                   7201:             return 'refused';
                   7202:         }
1.1028    raeburn  7203:     } elsif (!&allowed('ccc',$udom)) {
                   7204:         return 'refused';
1.84      www      7205:     }
1.1011    raeburn  7206: # --------------------------------------------------------------- Get Unique ID
                   7207:     my $uname;
                   7208:     if ($cnum =~ /^$match_courseid$/) {
                   7209:         my $chome=&homeserver($cnum,$udom,'true');
                   7210:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7211:             $uname = $cnum;
                   7212:         } else {
1.1038    raeburn  7213:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7214:         }
                   7215:     } else {
1.1038    raeburn  7216:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7217:     }
                   7218:     return $uname if ($uname =~ /^error/);
                   7219: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7220:     if (!defined($course_server)) {
                   7221:         if (defined(&domain($udom,'primary'))) {
                   7222:             $course_server = &domain($udom,'primary');
                   7223:         } else {
                   7224:             $course_server = $env{'user.home'}; 
                   7225:         }
                   7226:     }
                   7227:     my %host_servers =
                   7228:         &Apache::lonnet::get_servers($udom,'library');
                   7229:     unless ($host_servers{$course_server}) {
                   7230:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7231:     }
1.84      www      7232: # ------------------------------------------------------------- Make the course
                   7233:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7234:                       $course_server);
1.84      www      7235:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7236:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7237:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7238: 	return 'error: no such course';
                   7239:     }
1.271     www      7240: # ----------------------------------------------------------------- Course made
1.516     raeburn  7241: # log existence
1.1029    raeburn  7242:     my $now = time;
1.918     raeburn  7243:     my $newcourse = {
                   7244:                     $udom.'_'.$uname => {
1.921     raeburn  7245:                                      description => $description,
                   7246:                                      inst_code   => $inst_code,
                   7247:                                      owner       => $course_owner,
                   7248:                                      type        => $crstype,
1.1029    raeburn  7249:                                      creator     => $env{'user.name'}.':'.
                   7250:                                                     $env{'user.domain'},
                   7251:                                      created     => $now,
                   7252:                                      context     => $context,
1.918     raeburn  7253:                                                 },
                   7254:                     };
1.921     raeburn  7255:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7256: # set toplevel url
1.271     www      7257:     my $topurl=$url;
                   7258:     unless ($nonstandard) {
                   7259: # ------------------------------------------ For standard courses, make top url
                   7260:         my $mapurl=&clutter($url);
1.278     www      7261:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7262:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7263: <map>
                   7264: <resource id="1" type="start"></resource>
                   7265: <resource id="2" src="$mapurl"></resource>
                   7266: <resource id="3" type="finish"></resource>
                   7267: <link index="1" from="1" to="2"></link>
                   7268: <link index="2" from="2" to="3"></link>
                   7269: </map>
                   7270: ENDINITMAP
                   7271:         $topurl=&declutter(
1.638     albertel 7272:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7273:                           );
                   7274:     }
                   7275: # ----------------------------------------------------------- Write preferences
1.84      www      7276:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7277:                      ('description'              => $description,
                   7278:                       'url'                      => $topurl,
                   7279:                       'internal.creator'         => $env{'user.name'}.':'.
                   7280:                                                     $env{'user.domain'},
                   7281:                       'internal.created'         => $now,
                   7282:                       'internal.creationcontext' => $context)
                   7283:                     );
1.84      www      7284:     return '/'.$udom.'/'.$uname;
                   7285: }
                   7286: 
1.1011    raeburn  7287: # ------------------------------------------------------------------- Create ID
                   7288: sub generate_coursenum {
1.1038    raeburn  7289:     my ($udom,$crstype) = @_;
1.1011    raeburn  7290:     my $domdesc = &domain($udom);
                   7291:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7292:     my $first;
                   7293:     if ($crstype eq 'Community') {
                   7294:         $first = '0';
                   7295:     } else {
                   7296:         $first = int(1+rand(9)); 
                   7297:     } 
                   7298:     my $uname=$first.
1.1011    raeburn  7299:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7300:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7301:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7302: # ----------------------------------------------- Make sure that does not exist
                   7303:     my $uhome=&homeserver($uname,$udom,'true');
                   7304:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7305:         if ($crstype eq 'Community') {
                   7306:             $first = '0';
                   7307:         } else {
                   7308:             $first = int(1+rand(9));
                   7309:         }
                   7310:         $uname=$first.
1.1011    raeburn  7311:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7312:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7313:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7314:         $uhome=&homeserver($uname,$udom,'true');
                   7315:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7316:             return 'error: unable to generate unique course-ID';
                   7317:         }
                   7318:     }
                   7319:     return $uname;
                   7320: }
                   7321: 
1.813     albertel 7322: sub is_course {
                   7323:     my ($cdom,$cnum) = @_;
                   7324:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7325: 				undef,'.');
1.813     albertel 7326:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7327:         return 1;
                   7328:     }
                   7329:     return 0;
                   7330: }
                   7331: 
1.1015    raeburn  7332: sub store_userdata {
                   7333:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7334:     my $result;
1.1016    raeburn  7335:     if ($datakey ne '') {
1.1013    raeburn  7336:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7337:             if ($udom eq '' || $uname eq '') {
                   7338:                 $udom = $env{'user.domain'};
                   7339:                 $uname = $env{'user.name'};
                   7340:             }
                   7341:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7342:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7343:                 $result = 'error: no_host';
                   7344:             } else {
                   7345:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7346:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7347: 
                   7348:                 my $namevalue='';
                   7349:                 foreach my $key (keys(%{$storehash})) {
                   7350:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7351:                 }
                   7352:                 $namevalue=~s/\&$//;
                   7353:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  7354:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  7355:             }
                   7356:         } else {
                   7357:             $result = 'error: data to store was not a hash reference'; 
                   7358:         }
                   7359:     } else {
                   7360:         $result= 'error: invalid requestkey'; 
                   7361:     }
                   7362:     return $result;
                   7363: }
                   7364: 
1.21      www      7365: # ---------------------------------------------------------- Assign Custom Role
                   7366: 
                   7367: sub assigncustomrole {
1.957     raeburn  7368:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7369:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7370:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7371: }
                   7372: 
                   7373: # ----------------------------------------------------------------- Revoke Role
                   7374: 
                   7375: sub revokerole {
1.957     raeburn  7376:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7377:     my $now=time;
1.965     raeburn  7378:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7379: }
                   7380: 
                   7381: # ---------------------------------------------------------- Revoke Custom Role
                   7382: 
                   7383: sub revokecustomrole {
1.957     raeburn  7384:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7385:     my $now=time;
1.357     www      7386:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7387:            $deleteflag,$selfenroll,$context);
1.17      www      7388: }
                   7389: 
1.533     banghart 7390: # ------------------------------------------------------------ Disk usage
1.535     albertel 7391: sub diskusage {
1.955     raeburn  7392:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7393:     $directorypath =~ s/\/$//;
                   7394:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7395:                        .&escape($getpropath).':'.&escape($uname).':'
                   7396:                        .&escape($udom),homeserver($uname,$udom));
                   7397:     if ($listing eq 'unknown_cmd') {
                   7398:         if ($getpropath) {
                   7399:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7400:         }
                   7401:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7402:     }
1.514     albertel 7403:     return $listing;
1.512     banghart 7404: }
                   7405: 
1.566     banghart 7406: sub is_locked {
1.1056.4.17  raeburn  7407:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7408:     my @check;
                   7409:     my $is_locked;
1.1056.4.14  raeburn  7410:     push(@check,$file_name);
1.613     albertel 7411:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7412: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7413:     my ($tmp)=keys(%locked);
                   7414:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7415:     
1.566     banghart 7416:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7417:         $is_locked = 'false';
                   7418:         foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17  raeburn  7419:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7420:                $is_locked = 'true';
1.1056.4.17  raeburn  7421:                if (ref($which) eq 'ARRAY') {
                   7422:                    push(@{$which},$entry);
                   7423:                } else {
                   7424:                    last;
                   7425:                }
1.745     raeburn  7426:            }
                   7427:        }
1.566     banghart 7428:     } else {
                   7429:         $is_locked = 'false';
                   7430:     }
1.1056.4.14  raeburn  7431:     return $is_locked;
1.566     banghart 7432: }
                   7433: 
1.759     albertel 7434: sub declutter_portfile {
                   7435:     my ($file) = @_;
1.833     albertel 7436:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7437:     return $file;
                   7438: }
                   7439: 
1.559     banghart 7440: # ------------------------------------------------------------- Mark as Read Only
                   7441: 
                   7442: sub mark_as_readonly {
                   7443:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7444:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7445:     my ($tmp)=keys(%current_permissions);
                   7446:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7447:     foreach my $file (@{$files}) {
1.759     albertel 7448: 	$file = &declutter_portfile($file);
1.561     banghart 7449:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7450:     }
1.613     albertel 7451:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7452:     return;
                   7453: }
                   7454: 
1.572     banghart 7455: # ------------------------------------------------------------Save Selected Files
                   7456: 
                   7457: sub save_selected_files {
                   7458:     my ($user, $path, @files) = @_;
                   7459:     my $filename = $user."savedfiles";
1.573     banghart 7460:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7461:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7462:     foreach my $file (@files) {
1.620     albertel 7463:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7464:     }
                   7465:     foreach my $file (@other_files) {
1.574     banghart 7466:         print (OUT $file."\n");
1.572     banghart 7467:     }
1.574     banghart 7468:     close (OUT);
1.572     banghart 7469:     return 'ok';
                   7470: }
                   7471: 
1.574     banghart 7472: sub clear_selected_files {
                   7473:     my ($user) = @_;
                   7474:     my $filename = $user."savedfiles";
                   7475:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7476:     print (OUT undef);
                   7477:     close (OUT);
                   7478:     return ("ok");    
                   7479: }
                   7480: 
1.572     banghart 7481: sub files_in_path {
                   7482:     my ($user, $path) = @_;
                   7483:     my $filename = $user."savedfiles";
                   7484:     my %return_files;
1.574     banghart 7485:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7486:     while (my $line_in = <IN>) {
1.574     banghart 7487:         chomp ($line_in);
                   7488:         my @paths_and_file = split (m!/!, $line_in);
                   7489:         my $file_part = pop (@paths_and_file);
                   7490:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7491:         $path_part.='/';
                   7492:         my $path_and_file = $path_part.$file_part;
                   7493:         if ($path_part eq $path) {
                   7494:             $return_files{$file_part}= 'selected';
                   7495:         }
                   7496:     }
1.574     banghart 7497:     close (IN);
                   7498:     return (\%return_files);
1.572     banghart 7499: }
                   7500: 
                   7501: # called in portfolio select mode, to show files selected NOT in current directory
                   7502: sub files_not_in_path {
                   7503:     my ($user, $path) = @_;
                   7504:     my $filename = $user."savedfiles";
                   7505:     my @return_files;
                   7506:     my $path_part;
1.800     albertel 7507:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7508:     while (my $line = <IN>) {
1.572     banghart 7509:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7510:         my @paths_and_file = split(m|/|, $line);
                   7511:         my $file_part = pop(@paths_and_file);
                   7512:         chomp($file_part);
                   7513:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7514:         $path_part .= '/';
                   7515:         my $path_and_file = $path_part.$file_part;
                   7516:         if ($path_part ne $path) {
1.800     albertel 7517:             push(@return_files, ($path_and_file));
1.572     banghart 7518:         }
                   7519:     }
1.800     albertel 7520:     close(OUT);
1.574     banghart 7521:     return (@return_files);
1.572     banghart 7522: }
                   7523: 
1.745     raeburn  7524: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7525: 
1.745     raeburn  7526: sub get_portfile_permissions {
                   7527:     my ($domain,$user) = @_;
1.613     albertel 7528:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7529:     my ($tmp)=keys(%current_permissions);
                   7530:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7531:     return \%current_permissions;
                   7532: }
                   7533: 
                   7534: #---------------------------------------------Get portfolio file access controls
                   7535: 
1.749     raeburn  7536: sub get_access_controls {
1.745     raeburn  7537:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7538:     my %access;
                   7539:     my $real_file = $file;
                   7540:     $file =~ s/\.meta$//;
1.745     raeburn  7541:     if (defined($file)) {
1.749     raeburn  7542:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7543:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7544:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7545:             }
                   7546:         }
1.745     raeburn  7547:     } else {
1.749     raeburn  7548:         foreach my $key (keys(%{$current_permissions})) {
                   7549:             if ($key =~ /\0accesscontrol$/) {
                   7550:                 if (defined($group)) {
                   7551:                     if ($key !~ m-^\Q$group\E/-) {
                   7552:                         next;
                   7553:                     }
                   7554:                 }
                   7555:                 my ($fullpath) = split(/\0/,$key);
                   7556:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7557:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7558:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7559:                     }
                   7560:                 }
                   7561:             }
                   7562:         }
                   7563:     }
                   7564:     return %access;
                   7565: }
                   7566: 
                   7567: sub modify_access_controls {
                   7568:     my ($file_name,$changes,$domain,$user)=@_;
                   7569:     my ($outcome,$deloutcome);
                   7570:     my %store_permissions;
                   7571:     my %new_values;
                   7572:     my %new_control;
                   7573:     my %translation;
                   7574:     my @deletions = ();
                   7575:     my $now = time;
                   7576:     if (exists($$changes{'activate'})) {
                   7577:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7578:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7579:             my $numnew = scalar(@newitems);
                   7580:             for (my $i=0; $i<$numnew; $i++) {
                   7581:                 my $newkey = $newitems[$i];
                   7582:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7583:                 if ($newkey =~ /^\d+:/) { 
                   7584:                     $newkey =~ s/^(\d+)/$newid/;
                   7585:                     $translation{$1} = $newid;
                   7586:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7587:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7588:                     $translation{$1} = $newid;
                   7589:                 }
1.749     raeburn  7590:                 $new_values{$file_name."\0".$newkey} = 
                   7591:                                           $$changes{'activate'}{$newitems[$i]};
                   7592:                 $new_control{$newkey} = $now;
                   7593:             }
                   7594:         }
                   7595:     }
                   7596:     my %todelete;
                   7597:     my %changed_items;
                   7598:     foreach my $action ('delete','update') {
                   7599:         if (exists($$changes{$action})) {
                   7600:             if (ref($$changes{$action}) eq 'HASH') {
                   7601:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7602:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7603:                     if ($action eq 'delete') { 
                   7604:                         $todelete{$itemnum} = 1;
                   7605:                     } else {
                   7606:                         $changed_items{$itemnum} = $key;
                   7607:                     }
                   7608:                 }
1.745     raeburn  7609:             }
                   7610:         }
1.749     raeburn  7611:     }
                   7612:     # get lock on access controls for file.
                   7613:     my $lockhash = {
                   7614:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7615:                                                        ':'.$env{'user.domain'},
                   7616:                    }; 
                   7617:     my $tries = 0;
                   7618:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7619:    
                   7620:     while (($gotlock ne 'ok') && $tries <3) {
                   7621:         $tries ++;
                   7622:         sleep 1;
                   7623:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7624:     }
                   7625:     if ($gotlock eq 'ok') {
                   7626:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7627:         my ($tmp)=keys(%curr_permissions);
                   7628:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7629:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7630:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7631:             if (ref($curr_controls) eq 'HASH') {
                   7632:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7633:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7634:                     if (defined($todelete{$itemnum})) {
                   7635:                         push(@deletions,$file_name."\0".$control_item);
                   7636:                     } else {
                   7637:                         if (defined($changed_items{$itemnum})) {
                   7638:                             $new_control{$changed_items{$itemnum}} = $now;
                   7639:                             push(@deletions,$file_name."\0".$control_item);
                   7640:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7641:                         } else {
                   7642:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7643:                         }
                   7644:                     }
1.745     raeburn  7645:                 }
                   7646:             }
                   7647:         }
1.970     raeburn  7648:         my ($group);
                   7649:         if (&is_course($domain,$user)) {
                   7650:             ($group,my $file) = split(/\//,$file_name,2);
                   7651:         }
1.749     raeburn  7652:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7653:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7654:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7655:         #  remove lock
                   7656:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7657:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7658:         my $sqlresult =
1.970     raeburn  7659:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7660:                                     $group);
1.749     raeburn  7661:     } else {
                   7662:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7663:     }
1.749     raeburn  7664:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7665: }
                   7666: 
1.827     raeburn  7667: sub make_public_indefinitely {
                   7668:     my ($requrl) = @_;
                   7669:     my $now = time;
                   7670:     my $action = 'activate';
                   7671:     my $aclnum = 0;
                   7672:     if (&is_portfolio_url($requrl)) {
                   7673:         my (undef,$udom,$unum,$file_name,$group) =
                   7674:             &parse_portfolio_url($requrl);
                   7675:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7676:         my %access_controls = &get_access_controls($current_perms,
                   7677:                                                    $group,$file_name);
                   7678:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7679:             my ($num,$scope,$end,$start) = 
                   7680:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7681:             if ($scope eq 'public') {
                   7682:                 if ($start <= $now && $end == 0) {
                   7683:                     $action = 'none';
                   7684:                 } else {
                   7685:                     $action = 'update';
                   7686:                     $aclnum = $num;
                   7687:                 }
                   7688:                 last;
                   7689:             }
                   7690:         }
                   7691:         if ($action eq 'none') {
                   7692:              return 'ok';
                   7693:         } else {
                   7694:             my %changes;
                   7695:             my $newend = 0;
                   7696:             my $newstart = $now;
                   7697:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7698:             $changes{$action}{$newkey} = {
                   7699:                 type => 'public',
                   7700:                 time => {
                   7701:                     start => $newstart,
                   7702:                     end   => $newend,
                   7703:                 },
                   7704:             };
                   7705:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7706:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7707:             return $outcome;
                   7708:         }
                   7709:     } else {
                   7710:         return 'invalid';
                   7711:     }
                   7712: }
                   7713: 
1.745     raeburn  7714: #------------------------------------------------------Get Marked as Read Only
                   7715: 
                   7716: sub get_marked_as_readonly {
                   7717:     my ($domain,$user,$what,$group) = @_;
                   7718:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7719:     my @readonly_files;
1.629     banghart 7720:     my $cmp1=$what;
                   7721:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7722:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7723:         if (defined($group)) {
                   7724:             if ($file_name !~ m-^\Q$group\E/-) {
                   7725:                 next;
                   7726:             }
                   7727:         }
1.561     banghart 7728:         if (ref($value) eq "ARRAY"){
                   7729:             foreach my $stored_what (@{$value}) {
1.629     banghart 7730:                 my $cmp2=$stored_what;
1.759     albertel 7731:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7732:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7733:                 }
1.629     banghart 7734:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7735:                     push(@readonly_files, $file_name);
1.745     raeburn  7736:                     last;
1.563     banghart 7737:                 } elsif (!defined($what)) {
                   7738:                     push(@readonly_files, $file_name);
1.745     raeburn  7739:                     last;
1.561     banghart 7740:                 }
                   7741:             }
1.745     raeburn  7742:         }
1.561     banghart 7743:     }
                   7744:     return @readonly_files;
                   7745: }
1.577     banghart 7746: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7747: 
1.577     banghart 7748: sub get_marked_as_readonly_hash {
1.745     raeburn  7749:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7750:     my %readonly_files;
1.745     raeburn  7751:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7752:         if (defined($group)) {
                   7753:             if ($file_name !~ m-^\Q$group\E/-) {
                   7754:                 next;
                   7755:             }
                   7756:         }
1.577     banghart 7757:         if (ref($value) eq "ARRAY"){
                   7758:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7759:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7760:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7761:                         if ($lock_descriptor eq 'graded') {
                   7762:                             $readonly_files{$file_name} = 'graded';
                   7763:                         } elsif ($lock_descriptor eq 'handback') {
                   7764:                             $readonly_files{$file_name} = 'handback';
                   7765:                         } else {
                   7766:                             if (!exists($readonly_files{$file_name})) {
                   7767:                                 $readonly_files{$file_name} = 'locked';
                   7768:                             }
                   7769:                         }
1.745     raeburn  7770:                     }
1.750     banghart 7771:                 } 
1.577     banghart 7772:             }
                   7773:         } 
                   7774:     }
                   7775:     return %readonly_files;
                   7776: }
1.559     banghart 7777: # ------------------------------------------------------------ Unmark as Read Only
                   7778: 
                   7779: sub unmark_as_readonly {
1.629     banghart 7780:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7781:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7782:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7783:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7784:     my $symb_crs = $what;
                   7785:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7786:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7787:     my ($tmp)=keys(%current_permissions);
                   7788:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7789:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7790:     foreach my $file (@readonly_files) {
1.759     albertel 7791: 	my $clean_file = &declutter_portfile($file);
                   7792: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7793: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7794:         my @new_locks;
                   7795:         my @del_keys;
                   7796:         if (ref($current_locks) eq "ARRAY"){
                   7797:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7798:                 my $compare=$locker;
1.749     raeburn  7799:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7800:                     $compare=join('',@{$locker});
1.746     raeburn  7801:                     if ($compare ne $symb_crs) {
                   7802:                         push(@new_locks, $locker);
                   7803:                     }
1.563     banghart 7804:                 }
                   7805:             }
1.650     albertel 7806:             if (scalar(@new_locks) > 0) {
1.563     banghart 7807:                 $current_permissions{$file} = \@new_locks;
                   7808:             } else {
                   7809:                 push(@del_keys, $file);
1.613     albertel 7810:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7811:                 delete($current_permissions{$file});
1.563     banghart 7812:             }
                   7813:         }
1.561     banghart 7814:     }
1.613     albertel 7815:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7816:     return;
                   7817: }
1.512     banghart 7818: 
1.17      www      7819: # ------------------------------------------------------------ Directory lister
                   7820: 
                   7821: sub dirlist {
1.955     raeburn  7822:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7823:     $uri=~s/^\///;
                   7824:     $uri=~s/\/$//;
1.253     stredwic 7825:     my ($udom, $uname);
1.955     raeburn  7826:     if ($getuserdir) {
1.253     stredwic 7827:         $udom = $userdomain;
                   7828:         $uname = $username;
1.955     raeburn  7829:     } else {
                   7830:         (undef,$udom,$uname)=split(/\//,$uri);
                   7831:         if(defined($userdomain)) {
                   7832:             $udom = $userdomain;
                   7833:         }
                   7834:         if(defined($username)) {
                   7835:             $uname = $username;
                   7836:         }
1.253     stredwic 7837:     }
1.955     raeburn  7838:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7839: 
1.955     raeburn  7840:     $dirRoot = $perlvar{'lonDocRoot'};
                   7841:     if (defined($getpropath)) {
                   7842:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7843:         $dirRoot =~ s/\/$//;
1.955     raeburn  7844:     } elsif (defined($getuserdir)) {
                   7845:         my $subdir=$uname.'__';
                   7846:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7847:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7848:                    ."/$udom/$subdir/$uname";
                   7849:     } elsif (defined($alternateRoot)) {
                   7850:         $dirRoot = $alternateRoot;
1.751     banghart 7851:     }
1.253     stredwic 7852: 
                   7853:     if($udom) {
                   7854:         if($uname) {
1.955     raeburn  7855:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7856:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7857:                               .':'.&escape($uname).':'.&escape($udom),
                   7858:                               &homeserver($uname,$udom));
                   7859:             if ($listing eq 'unknown_cmd') {
                   7860:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7861:                                   &homeserver($uname,$udom));
                   7862:             } else {
                   7863:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7864:             }
1.605     matthew  7865:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7866:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7867: 				  &homeserver($uname,$udom));
1.605     matthew  7868:                 @listing_results = split(/:/,$listing);
                   7869:             } else {
                   7870:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7871:             }
                   7872:             return @listing_results;
1.955     raeburn  7873:         } elsif(!$alternateRoot) {
1.800     albertel 7874:             my %allusers;
1.841     albertel 7875: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7876:  	    foreach my $tryserver (keys(%servers)) {
                   7877:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7878:                                   &escape($udom),$tryserver);
                   7879:                 if ($listing eq 'unknown_cmd') {
                   7880: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7881: 				      $udom, $tryserver);
                   7882:                 } else {
                   7883:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7884:                 }
1.841     albertel 7885: 		if ($listing eq 'unknown_cmd') {
                   7886: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7887: 				      $udom, $tryserver);
                   7888: 		    @listing_results = split(/:/,$listing);
                   7889: 		} else {
                   7890: 		    @listing_results =
                   7891: 			map { &unescape($_); } split(/:/,$listing);
                   7892: 		}
                   7893: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7894: 		    $listing_results[0] ne 'empty'       &&
                   7895: 		    $listing_results[0] ne 'con_lost') {
                   7896: 		    foreach my $line (@listing_results) {
                   7897: 			my ($entry) = split(/&/,$line,2);
                   7898: 			$allusers{$entry} = 1;
                   7899: 		    }
                   7900: 		}
1.253     stredwic 7901:             }
                   7902:             my $alluserstr='';
1.800     albertel 7903:             foreach my $user (sort(keys(%allusers))) {
                   7904:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7905:             }
                   7906:             $alluserstr=~s/:$//;
                   7907:             return split(/:/,$alluserstr);
                   7908:         } else {
1.800     albertel 7909:             return ('missing user name');
1.253     stredwic 7910:         }
1.955     raeburn  7911:     } elsif(!defined($getpropath)) {
1.841     albertel 7912:         my @all_domains = sort(&all_domains());
1.955     raeburn  7913:         foreach my $domain (@all_domains) {
                   7914:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7915:         }
                   7916:         return @all_domains;
                   7917:     } else {
1.800     albertel 7918:         return ('missing domain');
1.275     stredwic 7919:     }
                   7920: }
                   7921: 
                   7922: # --------------------------------------------- GetFileTimestamp
                   7923: # This function utilizes dirlist and returns the date stamp for
                   7924: # when it was last modified.  It will also return an error of -1
                   7925: # if an error occurs
                   7926: 
                   7927: sub GetFileTimestamp {
1.955     raeburn  7928:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7929:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7930:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7931:     my ($fileStat) = 
                   7932:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7933:                                  undef,$getuserdir);
1.275     stredwic 7934:     my @stats = split('&', $fileStat);
                   7935:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7936:         # @stats contains first the filename, then the stat output
                   7937:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7938:     } else {
                   7939:         return -1;
1.253     stredwic 7940:     }
1.26      www      7941: }
                   7942: 
1.712     albertel 7943: sub stat_file {
                   7944:     my ($uri) = @_;
1.787     albertel 7945:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7946: 
1.955     raeburn  7947:     my ($udom,$uname,$file);
1.712     albertel 7948:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7949: 	($udom,$uname,$file) =
1.811     albertel 7950: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7951: 	$file = 'userfiles/'.$file;
                   7952:     }
                   7953:     if ($uri =~ m-^/res/-) {
                   7954: 	($udom,$uname) = 
1.807     albertel 7955: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7956: 	$file = $uri;
                   7957:     }
                   7958: 
                   7959:     if (!$udom || !$uname || !$file) {
                   7960: 	# unable to handle the uri
                   7961: 	return ();
                   7962:     }
1.956     raeburn  7963:     my $getpropath;
                   7964:     if ($file =~ /^userfiles\//) {
                   7965:         $getpropath = 1;
                   7966:     }
1.955     raeburn  7967:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7968:     my @stats = split('&', $result);
1.721     banghart 7969:     
1.712     albertel 7970:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7971: 	shift(@stats); #filename is first
                   7972: 	return @stats;
                   7973:     }
                   7974:     return ();
                   7975: }
                   7976: 
1.26      www      7977: # -------------------------------------------------------- Value of a Condition
                   7978: 
1.713     albertel 7979: # gets the value of a specific preevaluated condition
                   7980: #    stored in the string  $env{user.state.<cid>}
                   7981: # or looks up a condition reference in the bighash and if if hasn't
                   7982: # already been evaluated recurses into docondval to get the value of
                   7983: # the condition, then memoizing it to 
                   7984: #   $env{user.state.<cid>.<condition>}
1.40      www      7985: sub directcondval {
                   7986:     my $number=shift;
1.620     albertel 7987:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7988: 	&Apache::lonuserstate::evalstate();
                   7989:     }
1.713     albertel 7990:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7991: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7992:     } elsif ($number =~ /^_/) {
                   7993: 	my $sub_condition;
                   7994: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7995: 		&GDBM_READER(),0640)) {
                   7996: 	    $sub_condition=$bighash{'conditions'.$number};
                   7997: 	    untie(%bighash);
                   7998: 	}
                   7999: 	my $value = &docondval($sub_condition);
1.949     raeburn  8000: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8001: 	return $value;
                   8002:     }
1.620     albertel 8003:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8004:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8005:     } else {
                   8006:        return 2;
                   8007:     }
                   8008: }
                   8009: 
1.713     albertel 8010: # get the collection of conditions for this resource
1.26      www      8011: sub condval {
                   8012:     my $condidx=shift;
1.54      www      8013:     my $allpathcond='';
1.713     albertel 8014:     foreach my $cond (split(/\|/,$condidx)) {
                   8015: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8016: 	    $allpathcond.=
                   8017: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8018: 	}
1.191     harris41 8019:     }
1.54      www      8020:     $allpathcond=~s/\|$//;
1.713     albertel 8021:     return &docondval($allpathcond);
                   8022: }
                   8023: 
                   8024: #evaluates an expression of conditions
                   8025: sub docondval {
                   8026:     my ($allpathcond) = @_;
                   8027:     my $result=0;
                   8028:     if ($env{'request.course.id'}
                   8029: 	&& defined($allpathcond)) {
                   8030: 	my $operand='|';
                   8031: 	my @stack;
                   8032: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8033: 	    if ($chunk eq '(') {
                   8034: 		push @stack,($operand,$result);
                   8035: 	    } elsif ($chunk eq ')') {
                   8036: 		my $before=pop @stack;
                   8037: 		if (pop @stack eq '&') {
                   8038: 		    $result=$result>$before?$before:$result;
                   8039: 		} else {
                   8040: 		    $result=$result>$before?$result:$before;
                   8041: 		}
                   8042: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8043: 		$operand=$chunk;
                   8044: 	    } else {
                   8045: 		my $new=directcondval($chunk);
                   8046: 		if ($operand eq '&') {
                   8047: 		    $result=$result>$new?$new:$result;
                   8048: 		} else {
                   8049: 		    $result=$result>$new?$result:$new;
                   8050: 		}
                   8051: 	    }
                   8052: 	}
1.26      www      8053:     }
                   8054:     return $result;
1.421     albertel 8055: }
                   8056: 
                   8057: # ---------------------------------------------------- Devalidate courseresdata
                   8058: 
                   8059: sub devalidatecourseresdata {
                   8060:     my ($coursenum,$coursedomain)=@_;
                   8061:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8062:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8063: }
                   8064: 
1.763     www      8065: 
1.200     www      8066: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8067: #
                   8068: #  Parameters:
                   8069: #      $coursenum    - Number of the course.
                   8070: #      $coursedomain - Domain at which the course was created.
                   8071: #  Returns:
                   8072: #     A hash of the course parameters along (I think) with timestamps
                   8073: #     and version info.
1.877     foxr     8074: 
1.624     albertel 8075: sub get_courseresdata {
                   8076:     my ($coursenum,$coursedomain)=@_;
1.200     www      8077:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8078:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8079:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8080:     my %dumpreply;
1.417     albertel 8081:     unless (defined($cached)) {
1.624     albertel 8082: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8083: 	$result=\%dumpreply;
1.251     albertel 8084: 	my ($tmp) = keys(%dumpreply);
                   8085: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8086: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8087: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8088: 	    return $tmp;
1.416     albertel 8089: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8090: 	    $result=undef;
1.599     albertel 8091: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8092: 	}
                   8093:     }
1.624     albertel 8094:     return $result;
                   8095: }
                   8096: 
1.633     albertel 8097: sub devalidateuserresdata {
                   8098:     my ($uname,$udom)=@_;
                   8099:     my $hashid="$udom:$uname";
                   8100:     &devalidate_cache_new('userres',$hashid);
                   8101: }
                   8102: 
1.624     albertel 8103: sub get_userresdata {
                   8104:     my ($uname,$udom)=@_;
                   8105:     #most student don\'t have any data set, check if there is some data
                   8106:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8107: 
                   8108:     my $hashid="$udom:$uname";
                   8109:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8110:     if (!defined($cached)) {
                   8111: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8112: 	$result=\%resourcedata;
                   8113: 	&do_cache_new('userres',$hashid,$result,600);
                   8114:     }
                   8115:     my ($tmp)=keys(%$result);
                   8116:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8117: 	return $result;
                   8118:     }
                   8119:     #error 2 occurs when the .db doesn't exist
                   8120:     if ($tmp!~/error: 2 /) {
1.672     albertel 8121: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8122: 		 " Trying to get resource data for ".
                   8123: 		 $uname." at ".$udom.": ".
                   8124: 		 $tmp."</font>");
                   8125:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8126: 	#&EXT_cache_set($udom,$uname);
                   8127: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8128: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8129:     }
                   8130:     return $tmp;
                   8131: }
1.879     foxr     8132: #----------------------------------------------- resdata - return resource data
                   8133: #  Purpose:
                   8134: #    Return resource data for either users or for a course.
                   8135: #  Parameters:
                   8136: #     $name      - Course/user name.
                   8137: #     $domain    - Name of the domain the user/course is registered on.
                   8138: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8139: #     @which     - Array of names of resources desired.
                   8140: #  Returns:
                   8141: #     The value of the first reasource in @which that is found in the
                   8142: #     resource hash.
                   8143: #  Exceptional Conditions:
                   8144: #     If the $type passed in is not valid (not the string 'course' or 
                   8145: #     'user', an undefined  reference is returned.
                   8146: #     If none of the resources are found, an undef is returned
1.624     albertel 8147: sub resdata {
                   8148:     my ($name,$domain,$type,@which)=@_;
                   8149:     my $result;
                   8150:     if ($type eq 'course') {
                   8151: 	$result=&get_courseresdata($name,$domain);
                   8152:     } elsif ($type eq 'user') {
                   8153: 	$result=&get_userresdata($name,$domain);
                   8154:     }
                   8155:     if (!ref($result)) { return $result; }    
1.251     albertel 8156:     foreach my $item (@which) {
1.927     albertel 8157: 	if (defined($result->{$item->[0]})) {
                   8158: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8159: 	}
1.250     albertel 8160:     }
1.291     albertel 8161:     return undef;
1.200     www      8162: }
                   8163: 
1.379     matthew  8164: #
                   8165: # EXT resource caching routines
                   8166: #
                   8167: 
                   8168: sub clear_EXT_cache_status {
1.383     albertel 8169:     &delenv('cache.EXT.');
1.379     matthew  8170: }
                   8171: 
                   8172: sub EXT_cache_status {
                   8173:     my ($target_domain,$target_user) = @_;
1.383     albertel 8174:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8175:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8176:         # We know already the user has no data
                   8177:         return 1;
                   8178:     } else {
                   8179:         return 0;
                   8180:     }
                   8181: }
                   8182: 
                   8183: sub EXT_cache_set {
                   8184:     my ($target_domain,$target_user) = @_;
1.383     albertel 8185:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8186:     #&appenv({$cachename => time});
1.379     matthew  8187: }
                   8188: 
1.28      www      8189: # --------------------------------------------------------- Value of a Variable
1.58      www      8190: sub EXT {
1.715     albertel 8191: 
1.395     albertel 8192:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8193:     unless ($varname) { return ''; }
1.218     albertel 8194:     #get real user name/domain, courseid and symb
                   8195:     my $courseid;
1.359     albertel 8196:     my $publicuser;
1.427     www      8197:     if ($symbparm) {
                   8198: 	$symbparm=&get_symb_from_alias($symbparm);
                   8199:     }
1.218     albertel 8200:     if (!($uname && $udom)) {
1.790     albertel 8201:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8202:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8203:     } else {
1.620     albertel 8204: 	$courseid=$env{'request.course.id'};
1.218     albertel 8205:     }
1.48      www      8206:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8207:     my $rest;
1.320     albertel 8208:     if (defined($therest[0])) {
1.48      www      8209:        $rest=join('.',@therest);
                   8210:     } else {
                   8211:        $rest='';
                   8212:     }
1.320     albertel 8213: 
1.57      www      8214:     my $qualifierrest=$qualifier;
                   8215:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8216:     my $spacequalifierrest=$space;
                   8217:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8218:     if ($realm eq 'user') {
1.48      www      8219: # --------------------------------------------------------------- user.resource
                   8220: 	if ($space eq 'resource') {
1.651     albertel 8221: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8222: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8223: 		 &&
1.744     albertel 8224: 		 ($symbparm eq &symbread()) ) {	
                   8225: 		# if we are in the middle of processing the resource the
                   8226: 		# get the value we are planning on committing
                   8227:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8228:                     return $Apache::lonhomework::results{$qualifierrest};
                   8229:                 } else {
                   8230:                     return $Apache::lonhomework::history{$qualifierrest};
                   8231:                 }
1.335     albertel 8232: 	    } else {
1.359     albertel 8233: 		my %restored;
1.620     albertel 8234: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8235: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8236: 		} else {
                   8237: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8238: 		}
1.335     albertel 8239: 		return $restored{$qualifierrest};
                   8240: 	    }
1.48      www      8241: # ----------------------------------------------------------------- user.access
                   8242:         } elsif ($space eq 'access') {
1.218     albertel 8243: 	    # FIXME - not supporting calls for a specific user
1.48      www      8244:             return &allowed($qualifier,$rest);
                   8245: # ------------------------------------------ user.preferences, user.environment
                   8246:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8247: 	    if (($uname eq $env{'user.name'}) &&
                   8248: 		($udom eq $env{'user.domain'})) {
                   8249: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8250: 	    } else {
1.359     albertel 8251: 		my %returnhash;
                   8252: 		if (!$publicuser) {
                   8253: 		    %returnhash=&userenvironment($udom,$uname,
                   8254: 						 $qualifierrest);
                   8255: 		}
1.218     albertel 8256: 		return $returnhash{$qualifierrest};
                   8257: 	    }
1.48      www      8258: # ----------------------------------------------------------------- user.course
                   8259:         } elsif ($space eq 'course') {
1.218     albertel 8260: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8261:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8262: # ------------------------------------------------------------------- user.role
                   8263:         } elsif ($space eq 'role') {
1.218     albertel 8264: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8265:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8266:             if ($qualifier eq 'value') {
                   8267: 		return $role;
                   8268:             } elsif ($qualifier eq 'extent') {
                   8269:                 return $where;
                   8270:             }
                   8271: # ----------------------------------------------------------------- user.domain
                   8272:         } elsif ($space eq 'domain') {
1.218     albertel 8273:             return $udom;
1.48      www      8274: # ------------------------------------------------------------------- user.name
                   8275:         } elsif ($space eq 'name') {
1.218     albertel 8276:             return $uname;
1.48      www      8277: # ---------------------------------------------------- Any other user namespace
1.29      www      8278:         } else {
1.359     albertel 8279: 	    my %reply;
                   8280: 	    if (!$publicuser) {
                   8281: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8282: 	    }
                   8283: 	    return $reply{$qualifierrest};
1.48      www      8284:         }
1.236     www      8285:     } elsif ($realm eq 'query') {
                   8286: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8287:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8288: 						[$spacequalifierrest]);
1.620     albertel 8289: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8290:    } elsif ($realm eq 'request') {
1.48      www      8291: # ------------------------------------------------------------- request.browser
                   8292:         if ($space eq 'browser') {
1.430     www      8293: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8294: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8295: 		    return 1;
                   8296: 		} else {
                   8297: 		    return 0;
                   8298: 		}
                   8299: 	    } else {
1.620     albertel 8300: 		return $env{'browser.'.$qualifier};
1.430     www      8301: 	    }
1.57      www      8302: # ------------------------------------------------------------ request.filename
                   8303:         } else {
1.620     albertel 8304:             return $env{'request.'.$spacequalifierrest};
1.29      www      8305:         }
1.28      www      8306:     } elsif ($realm eq 'course') {
1.48      www      8307: # ---------------------------------------------------------- course.description
1.620     albertel 8308:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8309:     } elsif ($realm eq 'resource') {
1.165     www      8310: 
1.620     albertel 8311: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8312: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8313: 	}
1.693     albertel 8314: 
                   8315: 	if ($space eq 'title') {
                   8316: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8317: 	    return &gettitle($symbparm);
                   8318: 	}
                   8319: 	
                   8320: 	if ($space eq 'map') {
                   8321: 	    my ($map) = &decode_symb($symbparm);
                   8322: 	    return &symbread($map);
                   8323: 	}
1.905     albertel 8324: 	if ($space eq 'filename') {
                   8325: 	    if ($symbparm) {
                   8326: 		return &clutter((&decode_symb($symbparm))[2]);
                   8327: 	    }
                   8328: 	    return &hreflocation('',$env{'request.filename'});
                   8329: 	}
1.693     albertel 8330: 
                   8331: 	my ($section, $group, @groups);
1.593     albertel 8332: 	my ($courselevelm,$courselevel);
1.539     albertel 8333: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8334: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8335: 
1.218     albertel 8336: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8337: 
1.60      www      8338: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8339: 	    my $symbp=$symbparm;
1.735     albertel 8340: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8341: 
                   8342: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8343: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8344: 
1.620     albertel 8345: 	    if (($env{'user.name'} eq $uname) &&
                   8346: 		($env{'user.domain'} eq $udom)) {
                   8347: 		$section=$env{'request.course.sec'};
1.733     raeburn  8348:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8349:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8350: 	    } else {
1.539     albertel 8351: 		if (! defined($usection)) {
1.551     albertel 8352: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8353: 		} else {
                   8354: 		    $section = $usection;
                   8355: 		}
1.733     raeburn  8356:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8357: 	    }
                   8358: 
                   8359: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8360: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8361: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8362: 
1.593     albertel 8363: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8364: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8365: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8366: 
1.60      www      8367: # ----------------------------------------------------------- first, check user
1.624     albertel 8368: 
                   8369: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8370: 				       ([$courselevelr,'resource'],
                   8371: 					[$courselevelm,'map'     ],
                   8372: 					[$courselevel, 'course'  ]));
1.931     albertel 8373: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8374: 
1.594     albertel 8375: # ------------------------------------------------ second, check some of course
1.684     raeburn  8376:             my $coursereply;
1.691     raeburn  8377:             if (@groups > 0) {
                   8378:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8379:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8380:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8381:             }
1.96      www      8382: 
1.684     raeburn  8383: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8384: 				  $env{'course.'.$courseid.'.domain'},
                   8385: 				  'course',
                   8386: 				  ([$seclevelr,   'resource'],
                   8387: 				   [$seclevelm,   'map'     ],
                   8388: 				   [$seclevel,    'course'  ],
                   8389: 				   [$courselevelr,'resource']));
                   8390: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8391: 
1.60      www      8392: # ------------------------------------------------------ third, check map parms
1.218     albertel 8393: 	    my %parmhash=();
                   8394: 	    my $thisparm='';
                   8395: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8396: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8397: 		    &GDBM_READER(),0640)) {
1.218     albertel 8398: 		$thisparm=$parmhash{$symbparm};
                   8399: 		untie(%parmhash);
                   8400: 	    }
1.927     albertel 8401: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8402: 	}
1.594     albertel 8403: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8404: 
1.218     albertel 8405: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8406: 	my $filename;
                   8407: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8408: 	if ($symbparm) {
1.409     www      8409: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8410: 	} else {
1.620     albertel 8411: 	    $filename=$env{'request.filename'};
1.282     albertel 8412: 	}
                   8413: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8414: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8415: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8416: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8417: 
1.927     albertel 8418: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8419: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8420: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8421: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8422: 				     $env{'course.'.$courseid.'.domain'},
                   8423: 				     'course',
1.927     albertel 8424: 				     ([$courselevelm,'map'   ],
                   8425: 				      [$courselevel, 'course']));
                   8426: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8427: 	}
1.145     www      8428: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8429: 	unless ($space eq '0') {
1.336     albertel 8430: 	    my @parts=split(/_/,$space);
                   8431: 	    my $id=pop(@parts);
                   8432: 	    my $part=join('_',@parts);
                   8433: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8434: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8435: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8436: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8437: 	}
1.395     albertel 8438: 	if ($recurse) { return undef; }
                   8439: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8440: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8441: # ---------------------------------------------------- Any other user namespace
                   8442:     } elsif ($realm eq 'environment') {
                   8443: # ----------------------------------------------------------------- environment
1.620     albertel 8444: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8445: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8446: 	} else {
1.770     albertel 8447: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8448: 		return '';
                   8449: 	    }
1.219     albertel 8450: 	    my %returnhash=&userenvironment($udom,$uname,
                   8451: 					    $spacequalifierrest);
                   8452: 	    return $returnhash{$spacequalifierrest};
                   8453: 	}
1.28      www      8454:     } elsif ($realm eq 'system') {
1.48      www      8455: # ----------------------------------------------------------------- system.time
                   8456: 	if ($space eq 'time') {
                   8457: 	    return time;
                   8458:         }
1.696     albertel 8459:     } elsif ($realm eq 'server') {
                   8460: # ----------------------------------------------------------------- system.time
                   8461: 	if ($space eq 'name') {
                   8462: 	    return $ENV{'SERVER_NAME'};
                   8463:         }
1.28      www      8464:     }
1.48      www      8465:     return '';
1.61      www      8466: }
                   8467: 
1.927     albertel 8468: sub get_reply {
                   8469:     my ($reply_value) = @_;
1.940     raeburn  8470:     if (ref($reply_value) eq 'ARRAY') {
                   8471:         if (wantarray) {
                   8472: 	    return @$reply_value;
                   8473:         }
                   8474:         return $reply_value->[0];
                   8475:     } else {
                   8476:         return $reply_value;
1.927     albertel 8477:     }
                   8478: }
                   8479: 
1.691     raeburn  8480: sub check_group_parms {
                   8481:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8482:     my @groupitems = ();
                   8483:     my $resultitem;
1.927     albertel 8484:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8485:     foreach my $group (@{$groups}) {
                   8486:         foreach my $level (@levels) {
1.927     albertel 8487:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8488:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8489:         }
                   8490:     }
                   8491:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8492:                             $env{'course.'.$courseid.'.domain'},
                   8493:                                      'course',@groupitems);
                   8494:     return $coursereply;
                   8495: }
                   8496: 
                   8497: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8498:     my ($courseid,@groups) = @_;
                   8499:     @groups = sort(@groups);
1.691     raeburn  8500:     return @groups;
                   8501: }
                   8502: 
1.395     albertel 8503: sub packages_tab_default {
                   8504:     my ($uri,$varname)=@_;
                   8505:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8506: 
                   8507:     my (@extension,@specifics,$do_default);
                   8508:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8509: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8510: 	if ($pack_type eq 'default') {
                   8511: 	    $do_default=1;
                   8512: 	} elsif ($pack_type eq 'extension') {
                   8513: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8514: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8515: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8516: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8517: 	}
                   8518:     }
                   8519:     # first look for a package that matches the requested part id
                   8520:     foreach my $package (@specifics) {
                   8521: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8522: 	next if ($pack_part ne $part);
                   8523: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8524: 	    return $packagetab{"$pack_type&$name&default"};
                   8525: 	}
                   8526:     }
                   8527:     # look for any possible matching non extension_ package
                   8528:     foreach my $package (@specifics) {
                   8529: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8530: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8531: 	    return $packagetab{"$pack_type&$name&default"};
                   8532: 	}
1.585     albertel 8533: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8534: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8535: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8536: 	}
                   8537:     }
1.738     albertel 8538:     # look for any posible extension_ match
                   8539:     foreach my $package (@extension) {
                   8540: 	my ($package,$pack_type)=@{$package};
                   8541: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8542: 	    return $packagetab{"$pack_type&$name&default"};
                   8543: 	}
                   8544: 	if (defined($packagetab{$package."&$name&default"})) {
                   8545: 	    return $packagetab{$package."&$name&default"};
                   8546: 	}
                   8547:     }
                   8548:     # look for a global default setting
                   8549:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8550: 	return $packagetab{"default&$name&default"};
                   8551:     }
1.395     albertel 8552:     return undef;
                   8553: }
                   8554: 
1.334     albertel 8555: sub add_prefix_and_part {
                   8556:     my ($prefix,$part)=@_;
                   8557:     my $keyroot;
                   8558:     if (defined($prefix) && $prefix !~ /^__/) {
                   8559: 	# prefix that has a part already
                   8560: 	$keyroot=$prefix;
                   8561:     } elsif (defined($prefix)) {
                   8562: 	# prefix that is missing a part
                   8563: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8564:     } else {
                   8565: 	# no prefix at all
                   8566: 	if (defined($part)) { $keyroot='_'.$part; }
                   8567:     }
                   8568:     return $keyroot;
                   8569: }
                   8570: 
1.71      www      8571: # ---------------------------------------------------------------- Get metadata
                   8572: 
1.599     albertel 8573: my %metaentry;
1.71      www      8574: sub metadata {
1.176     www      8575:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8576:     $uri=&declutter($uri);
1.288     albertel 8577:     # if it is a non metadata possible uri return quickly
1.529     albertel 8578:     if (($uri eq '') || 
                   8579: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8580: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.20  raeburn  8581:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$}) || ($uri =~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.924     albertel 8582: 	return undef;
                   8583:     }
                   8584:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8585: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8586: 	return undef;
1.288     albertel 8587:     }
1.73      www      8588:     my $filename=$uri;
                   8589:     $uri=~s/\.meta$//;
1.172     www      8590: #
                   8591: # Is the metadata already cached?
1.177     www      8592: # Look at timestamp of caching
1.172     www      8593: # Everything is cached by the main uri, libraries are never directly cached
                   8594: #
1.428     albertel 8595:     if (!defined($liburi)) {
1.599     albertel 8596: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8597: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8598:     }
                   8599:     {
1.172     www      8600: #
                   8601: # Is this a recursive call for a library?
                   8602: #
1.599     albertel 8603: #	if (! exists($metacache{$uri})) {
                   8604: #	    $metacache{$uri}={};
                   8605: #	}
1.924     albertel 8606: 	my $cachetime = 60*60;
1.171     www      8607:         if ($liburi) {
                   8608: 	    $liburi=&declutter($liburi);
                   8609:             $filename=$liburi;
1.401     bowersj2 8610:         } else {
1.599     albertel 8611: 	    &devalidate_cache_new('meta',$uri);
                   8612: 	    undef(%metaentry);
1.401     bowersj2 8613: 	}
1.140     www      8614:         my %metathesekeys=();
1.73      www      8615:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8616: 	my $metastring;
1.924     albertel 8617: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8618: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8619: 	    $metastring = 
1.929     albertel 8620: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8621: 					  ('grade_target' => 'meta'));
                   8622: 	    $cachetime = 1; # only want this cached in the child not long term
                   8623: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8624: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8625: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8626: 	    $metastring=&getfile($file);
1.489     albertel 8627: 	}
1.208     albertel 8628:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8629:         my $token;
1.140     www      8630:         undef %metathesekeys;
1.71      www      8631:         while ($token=$parser->get_token) {
1.339     albertel 8632: 	    if ($token->[0] eq 'S') {
                   8633: 		if (defined($token->[2]->{'package'})) {
1.172     www      8634: #
                   8635: # This is a package - get package info
                   8636: #
1.339     albertel 8637: 		    my $package=$token->[2]->{'package'};
                   8638: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8639: 		    if (defined($token->[2]->{'id'})) { 
                   8640: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8641: 		    }
1.599     albertel 8642: 		    if ($metaentry{':packages'}) {
                   8643: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8644: 		    } else {
1.599     albertel 8645: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8646: 		    }
1.736     albertel 8647: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8648: 			my $part=$keyroot;
                   8649: 			$part=~s/^\_//;
1.736     albertel 8650: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8651: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8652: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8653: 			    # ignore package.tab specified default values
                   8654:                             # here &package_tab_default() will fetch those
                   8655: 			    if ($subp eq 'default') { next; }
1.736     albertel 8656: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8657: 			    my $unikey;
                   8658: 			    if ($pack =~ /_0$/) {
                   8659: 				$unikey='parameter_0_'.$name;
                   8660: 				$part=0;
                   8661: 			    } else {
                   8662: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8663: 			    }
1.339     albertel 8664: 			    if ($subp eq 'display') {
                   8665: 				$value.=' [Part: '.$part.']';
                   8666: 			    }
1.599     albertel 8667: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8668: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8669: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8670: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8671: 			    }
1.599     albertel 8672: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8673: 				$metaentry{':'.$unikey}=
                   8674: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8675: 			    }
1.339     albertel 8676: 			}
                   8677: 		    }
                   8678: 		} else {
1.172     www      8679: #
                   8680: # This is not a package - some other kind of start tag
1.339     albertel 8681: #
                   8682: 		    my $entry=$token->[1];
                   8683: 		    my $unikey;
                   8684: 		    if ($entry eq 'import') {
                   8685: 			$unikey='';
                   8686: 		    } else {
                   8687: 			$unikey=$entry;
                   8688: 		    }
                   8689: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8690: 
                   8691: 		    if (defined($token->[2]->{'id'})) { 
                   8692: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8693: 		    }
1.175     www      8694: 
1.339     albertel 8695: 		    if ($entry eq 'import') {
1.175     www      8696: #
                   8697: # Importing a library here
1.339     albertel 8698: #
                   8699: 			if ($depthcount<20) {
                   8700: 			    my $location=$parser->get_text('/import');
                   8701: 			    my $dir=$filename;
                   8702: 			    $dir=~s|[^/]*$||;
                   8703: 			    $location=&filelocation($dir,$location);
1.736     albertel 8704: 			    my $metadata = 
                   8705: 				&metadata($uri,'keys', $location,$unikey,
                   8706: 					  $depthcount+1);
                   8707: 			    foreach my $meta (split(',',$metadata)) {
                   8708: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8709: 				$metathesekeys{$meta}=1;
1.339     albertel 8710: 			    }
                   8711: 			}
                   8712: 		    } else { 
                   8713: 			if (defined($token->[2]->{'name'})) { 
                   8714: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8715: 			}
                   8716: 			$metathesekeys{$unikey}=1;
1.736     albertel 8717: 			foreach my $param (@{$token->[3]}) {
                   8718: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8719: 				$token->[2]->{$param};
1.339     albertel 8720: 			}
                   8721: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8722: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8723: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8724: 		 # only ws inside the tag, and not in default, so use default
                   8725: 		 # as value
1.599     albertel 8726: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8727: 			} elsif ( $internaltext =~ /\S/ ) {
                   8728: 		  # something interesting inside the tag
                   8729: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8730: 			} else {
1.908     albertel 8731: 		  # no interesting values, don't set a default
1.339     albertel 8732: 			}
1.172     www      8733: # end of not-a-package not-a-library import
1.339     albertel 8734: 		    }
1.172     www      8735: # end of not-a-package start tag
1.339     albertel 8736: 		}
1.172     www      8737: # the next is the end of "start tag"
1.339     albertel 8738: 	    }
                   8739: 	}
1.483     albertel 8740: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8741: 	$extension = lc($extension);
                   8742: 	if ($extension eq 'htm') { $extension='html'; }
                   8743: 
1.737     albertel 8744: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8745: 	    #no specific packages #how's our extension
                   8746: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8747: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8748: 					 \%metathesekeys);
                   8749: 	}
1.883     albertel 8750: 
                   8751: 	if (!exists($metaentry{':packages'})
                   8752: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8753: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8754: 		#no specific packages well let's get default then
                   8755: 		if ($key!~/^default&/) { next; }
1.488     albertel 8756: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8757: 					     \%metathesekeys);
                   8758: 	    }
                   8759: 	}
1.338     www      8760: # are there custom rights to evaluate
1.599     albertel 8761: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8762: 
1.338     www      8763:     #
                   8764:     # Importing a rights file here
1.339     albertel 8765:     #
                   8766: 	    unless ($depthcount) {
1.599     albertel 8767: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8768: 		my $dir=$filename;
                   8769: 		$dir=~s|[^/]*$||;
                   8770: 		$location=&filelocation($dir,$location);
1.736     albertel 8771: 		my $rights_metadata =
                   8772: 		    &metadata($uri,'keys',$location,'_rights',
                   8773: 			      $depthcount+1);
                   8774: 		foreach my $rights (split(',',$rights_metadata)) {
                   8775: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8776: 		    $metathesekeys{$rights}=1;
1.339     albertel 8777: 		}
                   8778: 	    }
                   8779: 	}
1.737     albertel 8780: 	# uniqifiy package listing
                   8781: 	my %seen;
                   8782: 	my @uniq_packages =
                   8783: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8784: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8785: 
                   8786: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8787: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8788: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8789: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8790: # this is the end of "was not already recently cached
1.71      www      8791:     }
1.599     albertel 8792:     return $metaentry{':'.$what};
1.261     albertel 8793: }
                   8794: 
1.488     albertel 8795: sub metadata_create_package_def {
1.483     albertel 8796:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8797:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8798:     if ($subp eq 'default') { next; }
                   8799:     
1.599     albertel 8800:     if (defined($metaentry{':packages'})) {
                   8801: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8802:     } else {
1.599     albertel 8803: 	$metaentry{':packages'}=$package;
1.483     albertel 8804:     }
                   8805:     my $value=$packagetab{$key};
                   8806:     my $unikey;
                   8807:     $unikey='parameter_0_'.$name;
1.599     albertel 8808:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8809:     $$metathesekeys{$unikey}=1;
1.599     albertel 8810:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8811: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8812:     }
1.599     albertel 8813:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8814: 	$metaentry{':'.$unikey}=
                   8815: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8816:     }
                   8817: }
                   8818: 
1.261     albertel 8819: sub metadata_generate_part0 {
                   8820:     my ($metadata,$metacache,$uri) = @_;
                   8821:     my %allnames;
1.737     albertel 8822:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8823: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8824: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8825: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8826: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8827: 	    $allnames{$name}=$part;
                   8828: 	  }
                   8829: 	}
                   8830:     }
                   8831:     foreach my $name (keys(%allnames)) {
                   8832:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8833:       my $key=":parameter_0_$name";
1.261     albertel 8834:       $$metacache{"$key.part"}='0';
                   8835:       $$metacache{"$key.name"}=$name;
1.428     albertel 8836:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8837: 					   $allnames{$name}.'_'.$name.
                   8838: 					   '.type'};
1.428     albertel 8839:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8840: 			     '.display'};
1.644     www      8841:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8842:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8843:       $$metacache{"$key.display"}=$olddis;
                   8844:     }
1.71      www      8845: }
                   8846: 
1.764     albertel 8847: # ------------------------------------------------------ Devalidate title cache
                   8848: 
                   8849: sub devalidate_title_cache {
                   8850:     my ($url)=@_;
                   8851:     if (!$env{'request.course.id'}) { return; }
                   8852:     my $symb=&symbread($url);
                   8853:     if (!$symb) { return; }
                   8854:     my $key=$env{'request.course.id'}."\0".$symb;
                   8855:     &devalidate_cache_new('title',$key);
                   8856: }
                   8857: 
1.1014    droeschl 8858: # ------------------------------------------------- Get the title of a course
                   8859: 
                   8860: sub current_course_title {
                   8861:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8862: }
1.301     www      8863: # ------------------------------------------------- Get the title of a resource
                   8864: 
                   8865: sub gettitle {
                   8866:     my $urlsymb=shift;
                   8867:     my $symb=&symbread($urlsymb);
1.534     albertel 8868:     if ($symb) {
1.620     albertel 8869: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8870: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8871: 	if (defined($cached)) { 
                   8872: 	    return $result;
                   8873: 	}
1.534     albertel 8874: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8875: 	my $title='';
1.907     albertel 8876: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8877: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8878: 	} else {
                   8879: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8880: 		    &GDBM_READER(),0640)) {
                   8881: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8882: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8883: 		untie(%bighash);
                   8884: 	    }
1.534     albertel 8885: 	}
                   8886: 	$title=~s/\&colon\;/\:/gs;
                   8887: 	if ($title) {
1.599     albertel 8888: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8889: 	}
                   8890: 	$urlsymb=$url;
                   8891:     }
                   8892:     my $title=&metadata($urlsymb,'title');
                   8893:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8894:     return $title;
1.301     www      8895: }
1.613     albertel 8896: 
1.614     albertel 8897: sub get_slot {
                   8898:     my ($which,$cnum,$cdom)=@_;
                   8899:     if (!$cnum || !$cdom) {
1.790     albertel 8900: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8901: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8902: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8903:     }
1.703     albertel 8904:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8905:     my %slotinfo;
                   8906:     if (exists($remembered{$key})) {
                   8907: 	$slotinfo{$which} = $remembered{$key};
                   8908:     } else {
                   8909: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8910: 	&Apache::lonhomework::showhash(%slotinfo);
                   8911: 	my ($tmp)=keys(%slotinfo);
                   8912: 	if ($tmp=~/^error:/) { return (); }
                   8913: 	$remembered{$key} = $slotinfo{$which};
                   8914:     }
1.616     albertel 8915:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8916: 	return %{$slotinfo{$which}};
                   8917:     }
                   8918:     return $slotinfo{$which};
1.614     albertel 8919: }
1.31      www      8920: # ------------------------------------------------- Update symbolic store links
                   8921: 
                   8922: sub symblist {
                   8923:     my ($mapname,%newhash)=@_;
1.438     www      8924:     $mapname=&deversion(&declutter($mapname));
1.31      www      8925:     my %hash;
1.620     albertel 8926:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8927:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8928:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8929: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8930: 		next if ($url eq 'last_known'
                   8931: 			 && $env{'form.no_update_last_known'});
                   8932: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8933: 						    $newhash{$url}->[1],
                   8934: 						    $newhash{$url}->[0]);
1.191     harris41 8935:             }
1.31      www      8936:             if (untie(%hash)) {
                   8937: 		return 'ok';
                   8938:             }
                   8939:         }
                   8940:     }
                   8941:     return 'error';
1.212     www      8942: }
                   8943: 
                   8944: # --------------------------------------------------------------- Verify a symb
                   8945: 
                   8946: sub symbverify {
1.510     www      8947:     my ($symb,$thisurl)=@_;
                   8948:     my $thisfn=$thisurl;
1.439     www      8949:     $thisfn=&declutter($thisfn);
1.215     www      8950: # direct jump to resource in page or to a sequence - will construct own symbs
                   8951:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8952: # check URL part
1.409     www      8953:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8954: 
1.431     www      8955:     unless ($url eq $thisfn) { return 0; }
1.213     www      8956: 
1.216     www      8957:     $symb=&symbclean($symb);
1.510     www      8958:     $thisurl=&deversion($thisurl);
1.439     www      8959:     $thisfn=&deversion($thisfn);
1.213     www      8960: 
                   8961:     my %bighash;
                   8962:     my $okay=0;
1.431     www      8963: 
1.620     albertel 8964:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8965:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8966:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8967:             $thisurl =~ s/\?.+$//;
                   8968:         }
1.510     www      8969:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8970:         unless ($ids) { 
1.1056.4.21  raeburn  8971:            my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
                   8972:            $ids=$bighash{$idkey};
1.216     www      8973:         }
                   8974:         if ($ids) {
                   8975: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8976: 	    foreach my $id (split(/\,/,$ids)) {
                   8977: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8978:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8979:                    $symb =~ s/\?.+$//;
                   8980:                }
1.216     www      8981:                if (
                   8982:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8983:    eq $symb) { 
1.620     albertel 8984: 		   if (($env{'request.role.adv'}) ||
1.1056.4.20  raeburn  8985: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   8986: 		       ($thisurl eq '/adm/navmaps')) {
1.582     albertel 8987: 		       $okay=1; 
                   8988: 		   }
                   8989: 	       }
1.216     www      8990: 	   }
                   8991:         }
1.213     www      8992: 	untie(%bighash);
                   8993:     }
                   8994:     return $okay;
1.31      www      8995: }
                   8996: 
1.210     www      8997: # --------------------------------------------------------------- Clean-up symb
                   8998: 
                   8999: sub symbclean {
                   9000:     my $symb=shift;
1.568     albertel 9001:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9002: # remove version from map
                   9003:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9004: 
1.210     www      9005: # remove version from URL
                   9006:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9007: 
1.507     www      9008: # remove wrapper
                   9009: 
1.510     www      9010:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9011:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9012:     return $symb;
1.409     www      9013: }
                   9014: 
                   9015: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9016: 
                   9017: sub encode_symb {
                   9018:     my ($map,$resid,$url)=@_;
                   9019:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9020: }
1.409     www      9021: 
                   9022: sub decode_symb {
1.568     albertel 9023:     my $symb=shift;
                   9024:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9025:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9026:     return (&fixversion($map),$resid,&fixversion($url));
                   9027: }
                   9028: 
                   9029: sub fixversion {
                   9030:     my $fn=shift;
1.609     banghart 9031:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9032:     my %bighash;
                   9033:     my $uri=&clutter($fn);
1.620     albertel 9034:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9035: # is this cached?
1.599     albertel 9036:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9037:     if (defined($cached)) { return $result; }
                   9038: # unfortunately not cached, or expired
1.620     albertel 9039:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9040: 	    &GDBM_READER(),0640)) {
                   9041:  	if ($bighash{'version_'.$uri}) {
                   9042:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9043:  	    unless (($version eq 'mostrecent') || 
                   9044: 		    ($version==&getversion($uri))) {
1.440     www      9045:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9046:  	    }
                   9047:  	}
                   9048:  	untie %bighash;
1.413     www      9049:     }
1.599     albertel 9050:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9051: }
                   9052: 
                   9053: sub deversion {
                   9054:     my $url=shift;
                   9055:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9056:     return $url;
1.210     www      9057: }
                   9058: 
1.31      www      9059: # ------------------------------------------------------ Return symb list entry
                   9060: 
                   9061: sub symbread {
1.249     www      9062:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9063:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9064:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9065: # no filename provided? try from environment
1.44      www      9066:     unless ($thisfn) {
1.620     albertel 9067:         if ($env{'request.symb'}) {
                   9068: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9069: 	}
1.620     albertel 9070: 	$thisfn=$env{'request.filename'};
1.44      www      9071:     }
1.569     albertel 9072:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9073: # is that filename actually a symb? Verify, clean, and return
                   9074:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9075: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9076: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9077: 	}
1.242     www      9078:     }
1.44      www      9079:     $thisfn=declutter($thisfn);
1.31      www      9080:     my %hash;
1.37      www      9081:     my %bighash;
                   9082:     my $syval='';
1.620     albertel 9083:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9084:         my $targetfn = $thisfn;
1.609     banghart 9085:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9086:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9087:         }
1.687     albertel 9088: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9089: 	    $targetfn=$1;
                   9090: 	}
1.620     albertel 9091:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9092:                       &GDBM_READER(),0640)) {
1.481     raeburn  9093: 	    $syval=$hash{$targetfn};
1.37      www      9094:             untie(%hash);
                   9095:         }
                   9096: # ---------------------------------------------------------- There was an entry
                   9097:         if ($syval) {
1.601     albertel 9098: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9099: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9100: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9101: 		    #return $env{$cache_str}='';
1.601     albertel 9102: 		#}    
                   9103: 		#$syval.=$1;
                   9104: 	    #}
1.37      www      9105:         } else {
                   9106: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9107:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9108:                             &GDBM_READER(),0640)) {
1.37      www      9109: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9110:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9111:               unless ($ids) { 
                   9112:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9113:               }
                   9114:               unless ($ids) {
                   9115: # alias?
                   9116: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9117:               }
1.37      www      9118:               if ($ids) {
                   9119: # ------------------------------------------------------------------- Has ID(s)
                   9120:                  my @possibilities=split(/\,/,$ids);
1.39      www      9121:                  if ($#possibilities==0) {
                   9122: # ----------------------------------------------- There is only one possibility
1.37      www      9123: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9124: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9125: 						    $resid,$thisfn);
1.249     www      9126:                  } elsif (!$donotrecurse) {
1.39      www      9127: # ------------------------------------------ There is more than one possibility
                   9128:                      my $realpossible=0;
1.800     albertel 9129:                      foreach my $id (@possibilities) {
                   9130: 			 my $file=$bighash{'src_'.$id};
1.39      www      9131:                          if (&allowed('bre',$file)) {
1.800     albertel 9132:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9133:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9134: 				$realpossible++;
1.626     albertel 9135:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9136: 						    $resid,$thisfn);
1.39      www      9137:                             }
                   9138: 			 }
1.191     harris41 9139:                      }
1.39      www      9140: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9141:                  } else {
                   9142:                      $syval='';
1.37      www      9143:                  }
                   9144: 	      }
                   9145:               untie(%bighash)
1.481     raeburn  9146:            }
1.31      www      9147:         }
1.62      www      9148:         if ($syval) {
1.620     albertel 9149: 	    return $env{$cache_str}=$syval;
1.62      www      9150:         }
1.31      www      9151:     }
1.949     raeburn  9152:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9153:     return $env{$cache_str}='';
1.31      www      9154: }
                   9155: 
                   9156: # ---------------------------------------------------------- Return random seed
                   9157: 
1.32      www      9158: sub numval {
                   9159:     my $txt=shift;
                   9160:     $txt=~tr/A-J/0-9/;
                   9161:     $txt=~tr/a-j/0-9/;
                   9162:     $txt=~tr/K-T/0-9/;
                   9163:     $txt=~tr/k-t/0-9/;
                   9164:     $txt=~tr/U-Z/0-5/;
                   9165:     $txt=~tr/u-z/0-5/;
                   9166:     $txt=~s/\D//g;
1.564     albertel 9167:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9168:     return int($txt);
1.368     albertel 9169: }
                   9170: 
1.484     albertel 9171: sub numval2 {
                   9172:     my $txt=shift;
                   9173:     $txt=~tr/A-J/0-9/;
                   9174:     $txt=~tr/a-j/0-9/;
                   9175:     $txt=~tr/K-T/0-9/;
                   9176:     $txt=~tr/k-t/0-9/;
                   9177:     $txt=~tr/U-Z/0-5/;
                   9178:     $txt=~tr/u-z/0-5/;
                   9179:     $txt=~s/\D//g;
                   9180:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9181:     my $total;
                   9182:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9183:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9184:     return int($total);
                   9185: }
                   9186: 
1.575     albertel 9187: sub numval3 {
                   9188:     use integer;
                   9189:     my $txt=shift;
                   9190:     $txt=~tr/A-J/0-9/;
                   9191:     $txt=~tr/a-j/0-9/;
                   9192:     $txt=~tr/K-T/0-9/;
                   9193:     $txt=~tr/k-t/0-9/;
                   9194:     $txt=~tr/U-Z/0-5/;
                   9195:     $txt=~tr/u-z/0-5/;
                   9196:     $txt=~s/\D//g;
                   9197:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9198:     my $total;
                   9199:     foreach my $val (@txts) { $total+=$val; }
                   9200:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9201:     return $total;
                   9202: }
                   9203: 
1.675     albertel 9204: sub digest {
                   9205:     my ($data)=@_;
                   9206:     my $digest=&Digest::MD5::md5($data);
                   9207:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9208:     my ($e,$f);
                   9209:     {
                   9210:         use integer;
                   9211:         $e=($a+$b);
                   9212:         $f=($c+$d);
                   9213:         if ($_64bit) {
                   9214:             $e=(($e<<32)>>32);
                   9215:             $f=(($f<<32)>>32);
                   9216:         }
                   9217:     }
                   9218:     if (wantarray) {
                   9219: 	return ($e,$f);
                   9220:     } else {
                   9221: 	my $g;
                   9222: 	{
                   9223: 	    use integer;
                   9224: 	    $g=($e+$f);
                   9225: 	    if ($_64bit) {
                   9226: 		$g=(($g<<32)>>32);
                   9227: 	    }
                   9228: 	}
                   9229: 	return $g;
                   9230:     }
                   9231: }
                   9232: 
1.368     albertel 9233: sub latest_rnd_algorithm_id {
1.675     albertel 9234:     return '64bit5';
1.366     albertel 9235: }
1.32      www      9236: 
1.503     albertel 9237: sub get_rand_alg {
                   9238:     my ($courseid)=@_;
1.790     albertel 9239:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9240:     if ($courseid) {
1.620     albertel 9241: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9242:     }
                   9243:     return &latest_rnd_algorithm_id();
                   9244: }
                   9245: 
1.562     albertel 9246: sub validCODE {
                   9247:     my ($CODE)=@_;
                   9248:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9249:     return 0;
                   9250: }
                   9251: 
1.491     albertel 9252: sub getCODE {
1.620     albertel 9253:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9254:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9255: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9256: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9257: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9258:     }
                   9259:     return undef;
                   9260: }
                   9261: 
1.31      www      9262: sub rndseed {
1.155     albertel 9263:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9264:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9265:     if (!defined($symb)) {
1.366     albertel 9266: 	unless ($symb=$wsymb) { return time; }
                   9267:     }
                   9268:     if (!$courseid) { $courseid=$wcourseid; }
                   9269:     if (!$domain) { $domain=$wdomain; }
                   9270:     if (!$username) { $username=$wusername }
1.503     albertel 9271:     my $which=&get_rand_alg();
1.803     albertel 9272: 
1.491     albertel 9273:     if (defined(&getCODE())) {
1.675     albertel 9274: 	if ($which eq '64bit5') {
                   9275: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9276: 	} elsif ($which eq '64bit4') {
1.575     albertel 9277: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9278: 	} else {
                   9279: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9280: 	}
1.675     albertel 9281:     } elsif ($which eq '64bit5') {
                   9282: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9283:     } elsif ($which eq '64bit4') {
                   9284: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9285:     } elsif ($which eq '64bit3') {
                   9286: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9287:     } elsif ($which eq '64bit2') {
                   9288: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9289:     } elsif ($which eq '64bit') {
                   9290: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9291:     }
                   9292:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9293: }
                   9294: 
                   9295: sub rndseed_32bit {
                   9296:     my ($symb,$courseid,$domain,$username)=@_;
                   9297:     {
                   9298: 	use integer;
                   9299: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9300: 	my $symbseed=numval($symb) << 22;
                   9301: 	my $namechck=unpack("%32C*",$username) << 17;
                   9302: 	my $nameseed=numval($username) << 12;
                   9303: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9304: 	my $courseseed=unpack("%32C*",$courseid);
                   9305: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9307: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9308: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9309: 	return $num;
                   9310:     }
                   9311: }
                   9312: 
                   9313: sub rndseed_64bit {
                   9314:     my ($symb,$courseid,$domain,$username)=@_;
                   9315:     {
                   9316: 	use integer;
                   9317: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9318: 	my $symbseed=numval($symb) << 10;
                   9319: 	my $namechck=unpack("%32S*",$username);
                   9320: 	
                   9321: 	my $nameseed=numval($username) << 21;
                   9322: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9323: 	my $courseseed=unpack("%32S*",$courseid);
                   9324: 	
                   9325: 	my $num1=$symbchck+$symbseed+$namechck;
                   9326: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9327: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9328: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9329: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9330: 	return "$num1,$num2";
1.155     albertel 9331:     }
1.366     albertel 9332: }
                   9333: 
1.443     albertel 9334: sub rndseed_64bit2 {
                   9335:     my ($symb,$courseid,$domain,$username)=@_;
                   9336:     {
                   9337: 	use integer;
                   9338: 	# strings need to be an even # of cahracters long, it it is odd the
                   9339:         # last characters gets thrown away
                   9340: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9341: 	my $symbseed=numval($symb) << 10;
                   9342: 	my $namechck=unpack("%32S*",$username.' ');
                   9343: 	
                   9344: 	my $nameseed=numval($username) << 21;
1.501     albertel 9345: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9346: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9347: 	
                   9348: 	my $num1=$symbchck+$symbseed+$namechck;
                   9349: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9350: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9351: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9352: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9353: 	return "$num1,$num2";
                   9354:     }
                   9355: }
                   9356: 
                   9357: sub rndseed_64bit3 {
                   9358:     my ($symb,$courseid,$domain,$username)=@_;
                   9359:     {
                   9360: 	use integer;
                   9361: 	# strings need to be an even # of cahracters long, it it is odd the
                   9362:         # last characters gets thrown away
                   9363: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9364: 	my $symbseed=numval2($symb) << 10;
                   9365: 	my $namechck=unpack("%32S*",$username.' ');
                   9366: 	
                   9367: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9368: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9369: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9370: 	
                   9371: 	my $num1=$symbchck+$symbseed+$namechck;
                   9372: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9373: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9374: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9375: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9376: 	
1.503     albertel 9377: 	return "$num1:$num2";
1.443     albertel 9378:     }
                   9379: }
                   9380: 
1.575     albertel 9381: sub rndseed_64bit4 {
                   9382:     my ($symb,$courseid,$domain,$username)=@_;
                   9383:     {
                   9384: 	use integer;
                   9385: 	# strings need to be an even # of cahracters long, it it is odd the
                   9386:         # last characters gets thrown away
                   9387: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9388: 	my $symbseed=numval3($symb) << 10;
                   9389: 	my $namechck=unpack("%32S*",$username.' ');
                   9390: 	
                   9391: 	my $nameseed=numval3($username) << 21;
                   9392: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9393: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9394: 	
                   9395: 	my $num1=$symbchck+$symbseed+$namechck;
                   9396: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9397: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9398: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9399: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9400: 	
                   9401: 	return "$num1:$num2";
                   9402:     }
                   9403: }
                   9404: 
1.675     albertel 9405: sub rndseed_64bit5 {
                   9406:     my ($symb,$courseid,$domain,$username)=@_;
                   9407:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9408:     return "$num1:$num2";
                   9409: }
                   9410: 
1.366     albertel 9411: sub rndseed_CODE_64bit {
                   9412:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9413:     {
1.366     albertel 9414: 	use integer;
1.443     albertel 9415: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9416: 	my $symbseed=numval2($symb);
1.491     albertel 9417: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9418: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9419: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9420: 	my $num1=$symbseed+$CODEchck;
                   9421: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9422: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9423: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9424: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9425: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9426: 	return "$num1:$num2";
1.366     albertel 9427:     }
                   9428: }
                   9429: 
1.575     albertel 9430: sub rndseed_CODE_64bit4 {
                   9431:     my ($symb,$courseid,$domain,$username)=@_;
                   9432:     {
                   9433: 	use integer;
                   9434: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9435: 	my $symbseed=numval3($symb);
                   9436: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9437: 	my $CODEseed=numval3(&getCODE());
                   9438: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9439: 	my $num1=$symbseed+$CODEchck;
                   9440: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9441: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9442: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9443: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9444: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9445: 	return "$num1:$num2";
                   9446:     }
                   9447: }
                   9448: 
1.675     albertel 9449: sub rndseed_CODE_64bit5 {
                   9450:     my ($symb,$courseid,$domain,$username)=@_;
                   9451:     my $code = &getCODE();
                   9452:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9453:     return "$num1:$num2";
                   9454: }
                   9455: 
1.366     albertel 9456: sub setup_random_from_rndseed {
                   9457:     my ($rndseed)=@_;
1.503     albertel 9458:     if ($rndseed =~/([,:])/) {
                   9459: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9460: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9461:     } else {
                   9462: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9463:     }
1.36      albertel 9464: }
                   9465: 
1.474     albertel 9466: sub latest_receipt_algorithm_id {
1.835     albertel 9467:     return 'receipt3';
1.474     albertel 9468: }
                   9469: 
1.480     www      9470: sub recunique {
                   9471:     my $fucourseid=shift;
                   9472:     my $unique;
1.835     albertel 9473:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9474: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9475: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9476:     } else {
                   9477: 	$unique=$perlvar{'lonReceipt'};
                   9478:     }
                   9479:     return unpack("%32C*",$unique);
                   9480: }
                   9481: 
                   9482: sub recprefix {
                   9483:     my $fucourseid=shift;
                   9484:     my $prefix;
1.835     albertel 9485:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9486: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9487: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9488:     } else {
                   9489: 	$prefix=$perlvar{'lonHostID'};
                   9490:     }
                   9491:     return unpack("%32C*",$prefix);
                   9492: }
                   9493: 
1.76      www      9494: sub ireceipt {
1.474     albertel 9495:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9496: 
                   9497:     my $return =&recprefix($fucourseid).'-';
                   9498: 
                   9499:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9500: 	$env{'request.state'} eq 'construct') {
                   9501: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9502: 	return $return;
                   9503:     }
                   9504: 
1.76      www      9505:     my $cuname=unpack("%32C*",$funame);
                   9506:     my $cudom=unpack("%32C*",$fudom);
                   9507:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9508:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9509:     my $cunique=&recunique($fucourseid);
1.474     albertel 9510:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9511:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9512: 
1.790     albertel 9513: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9514: 			       
                   9515: 	$return.= ($cunique%$cuname+
                   9516: 		   $cunique%$cudom+
                   9517: 		   $cusymb%$cuname+
                   9518: 		   $cusymb%$cudom+
                   9519: 		   $cucourseid%$cuname+
                   9520: 		   $cucourseid%$cudom+
                   9521: 		   $cpart%$cuname+
                   9522: 		   $cpart%$cudom);
                   9523:     } else {
                   9524: 	$return.= ($cunique%$cuname+
                   9525: 		   $cunique%$cudom+
                   9526: 		   $cusymb%$cuname+
                   9527: 		   $cusymb%$cudom+
                   9528: 		   $cucourseid%$cuname+
                   9529: 		   $cucourseid%$cudom);
                   9530:     }
                   9531:     return $return;
1.76      www      9532: }
                   9533: 
                   9534: sub receipt {
1.474     albertel 9535:     my ($part)=@_;
1.790     albertel 9536:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9537:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9538: }
1.260     ng       9539: 
1.790     albertel 9540: sub whichuser {
                   9541:     my ($passedsymb)=@_;
                   9542:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9543:     if (defined($env{'form.grade_symb'})) {
                   9544: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9545: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9546: 	if (!$allowed &&
                   9547: 	    exists($env{'request.course.sec'}) &&
                   9548: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9549: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9550: 			      '/'.$env{'request.course.sec'});
                   9551: 	}
                   9552: 	if ($allowed) {
                   9553: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9554: 	    $courseid=$tmp_courseid;
                   9555: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9556: 	    ($name)=&get_env_multiple('form.grade_username');
                   9557: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9558: 	}
                   9559:     }
                   9560:     if (!$passedsymb) {
                   9561: 	$symb=&symbread();
                   9562:     } else {
                   9563: 	$symb=$passedsymb;
                   9564:     }
                   9565:     $courseid=$env{'request.course.id'};
                   9566:     $domain=$env{'user.domain'};
                   9567:     $name=$env{'user.name'};
                   9568:     if ($name eq 'public' && $domain eq 'public') {
                   9569: 	if (!defined($env{'form.username'})) {
                   9570: 	    $env{'form.username'}.=time.rand(10000000);
                   9571: 	}
                   9572: 	$name.=$env{'form.username'};
                   9573:     }
                   9574:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9575: 
                   9576: }
                   9577: 
1.36      albertel 9578: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9579: # returns either the contents of the file or 
                   9580: # -1 if the file doesn't exist
1.481     raeburn  9581: #
                   9582: # if the target is a file that was uploaded via DOCS, 
                   9583: # a check will be made to see if a current copy exists on the local server,
                   9584: # if it does this will be served, otherwise a copy will be retrieved from
                   9585: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9586: # the local server.   
1.472     albertel 9587: 
1.36      albertel 9588: sub getfile {
1.538     albertel 9589:     my ($file) = @_;
1.609     banghart 9590:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9591:     &repcopy($file);
                   9592:     return &readfile($file);
                   9593: }
                   9594: 
                   9595: sub repcopy_userfile {
                   9596:     my ($file)=@_;
1.609     banghart 9597:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9598:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9599:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9600: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9601:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9602:     if (-e "$file") {
1.828     www      9603: # we already have a local copy, check it out
1.538     albertel 9604: 	my @fileinfo = stat($file);
1.828     www      9605: 	my $rtncode;
                   9606: 	my $info;
1.538     albertel 9607: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9608: 	if ($lwpresp ne 'ok') {
1.828     www      9609: # there is no such file anymore, even though we had a local copy
1.482     albertel 9610: 	    if ($rtncode eq '404') {
1.538     albertel 9611: 		unlink($file);
1.482     albertel 9612: 	    }
                   9613: 	    return -1;
                   9614: 	}
                   9615: 	if ($info < $fileinfo[9]) {
1.828     www      9616: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9617: 	    return 'ok';
1.828     www      9618: 	} else {
                   9619: # the file is outdated, get rid of it
                   9620: 	    unlink($file);
1.482     albertel 9621: 	}
1.828     www      9622:     }
                   9623: # one way or the other, at this point, we don't have the file
                   9624: # construct the correct path for the file
                   9625:     my @parts = ($cdom,$cnum); 
                   9626:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9627: 	push @parts, split(/\//,$1);
                   9628:     }
                   9629:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9630:     foreach my $part (@parts) {
                   9631: 	$path .= '/'.$part;
                   9632: 	if (!-e $path) {
                   9633: 	    mkdir($path,0770);
1.482     albertel 9634: 	}
                   9635:     }
1.828     www      9636: # now the path exists for sure
                   9637: # get a user agent
                   9638:     my $ua=new LWP::UserAgent;
                   9639:     my $transferfile=$file.'.in.transfer';
                   9640: # FIXME: this should flock
                   9641:     if (-e $transferfile) { return 'ok'; }
                   9642:     my $request;
                   9643:     $uri=~s/^\///;
1.980     raeburn  9644:     my $homeserver = &homeserver($cnum,$cdom);
                   9645:     my $protocol = $protocol{$homeserver};
                   9646:     $protocol = 'http' if ($protocol ne 'https');
                   9647:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9648:     my $response=$ua->request($request,$transferfile);
                   9649: # did it work?
                   9650:     if ($response->is_error()) {
                   9651: 	unlink($transferfile);
                   9652: 	&logthis("Userfile repcopy failed for $uri");
                   9653: 	return -1;
                   9654:     }
                   9655: # worked, rename the transfer file
                   9656:     rename($transferfile,$file);
1.607     raeburn  9657:     return 'ok';
1.481     raeburn  9658: }
                   9659: 
1.517     albertel 9660: sub tokenwrapper {
                   9661:     my $uri=shift;
1.980     raeburn  9662:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9663:     $uri=~s|^/||;
1.620     albertel 9664:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9665:     my $token=$1;
1.552     albertel 9666:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9667:     if ($udom && $uname && $file) {
                   9668: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9669:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9670:         my $homeserver = &homeserver($uname,$udom);
                   9671:         my $protocol = $protocol{$homeserver};
                   9672:         $protocol = 'http' if ($protocol ne 'https');
                   9673:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9674:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9675:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9676:     } else {
                   9677:         return '/adm/notfound.html';
                   9678:     }
                   9679: }
                   9680: 
1.828     www      9681: # call with reqtype HEAD: get last modification time
                   9682: # call with reqtype GET: get the file contents
                   9683: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9684: #
1.481     raeburn  9685: sub getuploaded {
                   9686:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9687:     $uri=~s/^\///;
1.980     raeburn  9688:     my $homeserver = &homeserver($cnum,$cdom);
                   9689:     my $protocol = $protocol{$homeserver};
                   9690:     $protocol = 'http' if ($protocol ne 'https');
                   9691:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9692:     my $ua=new LWP::UserAgent;
                   9693:     my $request=new HTTP::Request($reqtype,$uri);
                   9694:     my $response=$ua->request($request);
                   9695:     $$rtncode = $response->code;
1.482     albertel 9696:     if (! $response->is_success()) {
                   9697: 	return 'failed';
                   9698:     }      
                   9699:     if ($reqtype eq 'HEAD') {
1.486     www      9700: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9701:     } elsif ($reqtype eq 'GET') {
                   9702: 	$$info = $response->content;
1.472     albertel 9703:     }
1.482     albertel 9704:     return 'ok';
1.36      albertel 9705: }
                   9706: 
1.481     raeburn  9707: sub readfile {
                   9708:     my $file = shift;
                   9709:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9710:     my $fh;
                   9711:     open($fh,"<$file");
                   9712:     my $a='';
1.800     albertel 9713:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9714:     return $a;
                   9715: }
                   9716: 
1.36      albertel 9717: sub filelocation {
1.590     banghart 9718:     my ($dir,$file) = @_;
                   9719:     my $location;
                   9720:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9721: 
                   9722:     if ($file =~ m-^/adm/-) {
                   9723: 	$file=~s-^/adm/wrapper/-/-;
                   9724: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9725:     }
1.882     albertel 9726: 
1.590     banghart 9727:     if ($file=~m:^/~:) { # is a contruction space reference
                   9728:         $location = $file;
                   9729:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9730:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9731: 	# is a correct contruction space reference
                   9732:         $location = $file;
1.956     raeburn  9733:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9734:         $location = $file;
1.609     banghart 9735:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9736:         my ($udom,$uname,$filename)=
1.811     albertel 9737:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9738:         my $home=&homeserver($uname,$udom);
                   9739:         my $is_me=0;
                   9740:         my @ids=&current_machine_ids();
                   9741:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9742:         if ($is_me) {
1.955     raeburn  9743:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9744:         } else {
                   9745:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9746:   	      $udom.'/'.$uname.'/'.$filename;
                   9747:         }
1.882     albertel 9748:     } elsif ($file =~ m-^/adm/-) {
                   9749: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9750:     } else {
                   9751:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9752:         $file=~s:^/res/:/:;
                   9753:         if ( !( $file =~ m:^/:) ) {
                   9754:             $location = $dir. '/'.$file;
                   9755:         } else {
                   9756:             $location = '/home/httpd/html/res'.$file;
                   9757:         }
1.59      albertel 9758:     }
1.590     banghart 9759:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9760:     while ($location=~m{/\.\./}) {
                   9761: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9762: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9763: 	} else {
                   9764: 	    $location=~ s{/\.\./}{/}g;
                   9765: 	}
                   9766:     } #remove dir/..
1.590     banghart 9767:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9768:     return $location;
1.46      www      9769: }
1.36      albertel 9770: 
1.46      www      9771: sub hreflocation {
                   9772:     my ($dir,$file)=@_;
1.980     raeburn  9773:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9774: 	$file=filelocation($dir,$file);
1.700     albertel 9775:     } elsif ($file=~m-^/adm/-) {
                   9776: 	$file=~s-^/adm/wrapper/-/-;
                   9777: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9778:     }
                   9779:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9780: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9781:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9782: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9783:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9784: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9785: 	    -/uploaded/$1/$2/-x;
1.46      www      9786:     }
1.913     albertel 9787:     if ($file=~ m{^/userfiles/}) {
                   9788: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9789:     }
1.462     albertel 9790:     return $file;
1.465     albertel 9791: }
                   9792: 
                   9793: sub current_machine_domains {
1.853     albertel 9794:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9795: }
                   9796: 
                   9797: sub machine_domains {
                   9798:     my ($hostname) = @_;
1.465     albertel 9799:     my @domains;
1.838     albertel 9800:     my %hostname = &all_hostnames();
1.465     albertel 9801:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9802: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9803: 	if ($hostname eq $name) {
1.844     albertel 9804: 	    push(@domains,&host_domain($id));
1.465     albertel 9805: 	}
                   9806:     }
                   9807:     return @domains;
                   9808: }
                   9809: 
                   9810: sub current_machine_ids {
1.853     albertel 9811:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9812: }
                   9813: 
                   9814: sub machine_ids {
                   9815:     my ($hostname) = @_;
                   9816:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9817:     my @ids;
1.888     albertel 9818:     my %name_to_host = &all_names();
1.889     albertel 9819:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9820: 	return @{ $name_to_host{$hostname} };
                   9821:     }
                   9822:     return;
1.31      www      9823: }
                   9824: 
1.824     raeburn  9825: sub additional_machine_domains {
                   9826:     my @domains;
                   9827:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9828:     while( my $line = <$fh>) {
                   9829:         $line =~ s/\s//g;
                   9830:         push(@domains,$line);
                   9831:     }
                   9832:     return @domains;
                   9833: }
                   9834: 
                   9835: sub default_login_domain {
                   9836:     my $domain = $perlvar{'lonDefDomain'};
                   9837:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9838:     foreach my $posdom (&current_machine_domains(),
                   9839:                         &additional_machine_domains()) {
                   9840:         if (lc($posdom) eq lc($testdomain)) {
                   9841:             $domain=$posdom;
                   9842:             last;
                   9843:         }
                   9844:     }
                   9845:     return $domain;
                   9846: }
                   9847: 
1.31      www      9848: # ------------------------------------------------------------- Declutters URLs
                   9849: 
                   9850: sub declutter {
                   9851:     my $thisfn=shift;
1.569     albertel 9852:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9853:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9854:     $thisfn=~s/^\///;
1.697     albertel 9855:     $thisfn=~s|^adm/wrapper/||;
                   9856:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9857:     $thisfn=~s/^res\///;
1.1032    raeburn  9858:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9859:         $thisfn=~s/\?.+$//;
                   9860:     }
1.268     www      9861:     return $thisfn;
                   9862: }
                   9863: 
                   9864: # ------------------------------------------------------------- Clutter up URLs
                   9865: 
                   9866: sub clutter {
                   9867:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9868:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9869: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9870:        $thisfn='/res'.$thisfn; 
                   9871:     }
1.1031    raeburn  9872:     if ($thisfn !~m|^/adm|) {
                   9873: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9874: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9875: 	} else {
                   9876: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9877: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9878: 	    if ($embstyle eq 'ssi'
                   9879: 		|| ($embstyle eq 'hdn')
                   9880: 		|| ($embstyle eq 'rat')
                   9881: 		|| ($embstyle eq 'prv')
                   9882: 		|| ($embstyle eq 'ign')) {
                   9883: 		#do nothing with these
                   9884: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9885: 		|| ($embstyle eq 'emb')
                   9886: 		|| ($embstyle eq 'wrp')) {
                   9887: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9888: 	    } elsif ($embstyle eq 'unk'
                   9889: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9890: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9891: 	    } else {
1.718     www      9892: #		&logthis("Got a blank emb style");
1.695     albertel 9893: 	    }
1.694     albertel 9894: 	}
                   9895:     }
1.31      www      9896:     return $thisfn;
1.12      www      9897: }
                   9898: 
1.787     albertel 9899: sub clutter_with_no_wrapper {
                   9900:     my $uri = &clutter(shift);
                   9901:     if ($uri =~ m-^/adm/-) {
                   9902: 	$uri =~ s-^/adm/wrapper/-/-;
                   9903: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9904:     }
                   9905:     return $uri;
                   9906: }
                   9907: 
1.557     albertel 9908: sub freeze_escape {
                   9909:     my ($value)=@_;
                   9910:     if (ref($value)) {
                   9911: 	$value=&nfreeze($value);
                   9912: 	return '__FROZEN__'.&escape($value);
                   9913:     }
                   9914:     return &escape($value);
                   9915: }
                   9916: 
1.11      www      9917: 
1.557     albertel 9918: sub thaw_unescape {
                   9919:     my ($value)=@_;
                   9920:     if ($value =~ /^__FROZEN__/) {
                   9921: 	substr($value,0,10,undef);
                   9922: 	$value=&unescape($value);
                   9923: 	return &thaw($value);
                   9924:     }
                   9925:     return &unescape($value);
                   9926: }
                   9927: 
1.436     albertel 9928: sub correct_line_ends {
                   9929:     my ($result)=@_;
                   9930:     $$result =~s/\r\n/\n/mg;
                   9931:     $$result =~s/\r/\n/mg;
1.415     albertel 9932: }
1.1       albertel 9933: # ================================================================ Main Program
                   9934: 
1.184     www      9935: sub goodbye {
1.204     albertel 9936:    &logthis("Starting Shut down");
1.443     albertel 9937: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9938:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9939: #converted
1.599     albertel 9940: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9941:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9942: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9943: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9944: #1.1 only
1.870     albertel 9945: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9946: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9947: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9948: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9949:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9950:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9951:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9952:    &flushcourselogs();
                   9953:    &logthis("Shutting down");
                   9954: }
                   9955: 
1.852     albertel 9956: sub get_dns {
1.869     albertel 9957:     my ($url,$func,$ignore_cache) = @_;
                   9958:     if (!$ignore_cache) {
                   9959: 	my ($content,$cached)=
                   9960: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9961: 	if ($cached) {
                   9962: 	    &$func($content);
                   9963: 	    return;
                   9964: 	}
                   9965:     }
                   9966: 
                   9967:     my %alldns;
1.852     albertel 9968:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9969:     foreach my $dns (<$config>) {
                   9970: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9971:         my $line = $1;
                   9972:         my ($host,$protocol) = split(/:/,$line);
                   9973:         if ($protocol ne 'https') {
                   9974:             $protocol = 'http';
                   9975:         }
                   9976: 	$alldns{$host} = $protocol;
1.869     albertel 9977:     }
                   9978:     while (%alldns) {
                   9979: 	my ($dns) = keys(%alldns);
1.852     albertel 9980: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9981: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9982: 	my $response=$ua->request($request);
1.979     raeburn  9983:         delete($alldns{$dns});
1.852     albertel 9984: 	next if ($response->is_error());
                   9985: 	my @content = split("\n",$response->content);
1.869     albertel 9986: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9987: 	&$func(\@content);
1.869     albertel 9988: 	return;
1.852     albertel 9989:     }
                   9990:     close($config);
1.871     albertel 9991:     my $which = (split('/',$url))[3];
                   9992:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9993:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9994:     my @content = <$config>;
                   9995:     &$func(\@content);
                   9996:     return;
1.852     albertel 9997: }
1.327     albertel 9998: # ------------------------------------------------------------ Read domain file
                   9999: {
1.852     albertel 10000:     my $loaded;
1.846     albertel 10001:     my %domain;
                   10002: 
1.852     albertel 10003:     sub parse_domain_tab {
                   10004: 	my ($lines) = @_;
                   10005: 	foreach my $line (@$lines) {
                   10006: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10007: 
1.846     albertel 10008: 	    chomp($line);
1.852     albertel 10009: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10010: 	    my %this_domain;
                   10011: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10012: 			       'lang_def', 'city', 'longi', 'lati',
                   10013: 			       'primary') {
                   10014: 		$this_domain{$field} = shift(@elements);
                   10015: 	    }
                   10016: 	    $domain{$name} = \%this_domain;
1.852     albertel 10017: 	}
                   10018:     }
1.864     albertel 10019: 
                   10020:     sub reset_domain_info {
                   10021: 	undef($loaded);
                   10022: 	undef(%domain);
                   10023:     }
                   10024: 
1.852     albertel 10025:     sub load_domain_tab {
1.869     albertel 10026: 	my ($ignore_cache) = @_;
                   10027: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10028: 	my $fh;
                   10029: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10030: 	    my @lines = <$fh>;
                   10031: 	    &parse_domain_tab(\@lines);
1.448     albertel 10032: 	}
1.852     albertel 10033: 	close($fh);
                   10034: 	$loaded = 1;
1.327     albertel 10035:     }
1.846     albertel 10036: 
                   10037:     sub domain {
1.852     albertel 10038: 	&load_domain_tab() if (!$loaded);
                   10039: 
1.846     albertel 10040: 	my ($name,$what) = @_;
                   10041: 	return if ( !exists($domain{$name}) );
                   10042: 
                   10043: 	if (!$what) {
                   10044: 	    return $domain{$name}{'description'};
                   10045: 	}
                   10046: 	return $domain{$name}{$what};
                   10047:     }
1.974     raeburn  10048: 
                   10049:     sub domain_info {
                   10050:         &load_domain_tab() if (!$loaded);
                   10051:         return %domain;
                   10052:     }
                   10053: 
1.327     albertel 10054: }
                   10055: 
                   10056: 
1.1       albertel 10057: # ------------------------------------------------------------- Read hosts file
                   10058: {
1.838     albertel 10059:     my %hostname;
1.844     albertel 10060:     my %hostdom;
1.845     albertel 10061:     my %libserv;
1.852     albertel 10062:     my $loaded;
1.888     albertel 10063:     my %name_to_host;
1.1056.4.6  raeburn  10064:     my %internetdom;
1.852     albertel 10065: 
                   10066:     sub parse_hosts_tab {
                   10067: 	my ($file) = @_;
                   10068: 	foreach my $configline (@$file) {
                   10069: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   10070: 	    next if ($configline =~ /^\^/);
                   10071: 	    chomp($configline);
1.1056.4.6  raeburn  10072: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10073: 	    $name=~s/\s//g;
                   10074: 	    if ($id && $domain && $role && $name) {
                   10075: 		$hostname{$id}=$name;
1.888     albertel 10076: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10077: 		$hostdom{$id}=$domain;
                   10078: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10079:                 if (defined($protocol)) {
                   10080:                     if ($protocol eq 'https') {
                   10081:                         $protocol{$id} = $protocol;
                   10082:                     } else {
                   10083:                         $protocol{$id} = 'http'; 
                   10084:                     }
1.968     raeburn  10085:                 } else {
1.969     raeburn  10086:                     $protocol{$id} = 'http';
1.968     raeburn  10087:                 }
1.1056.4.6  raeburn  10088:                 if (defined($intdom)) {
                   10089:                     $internetdom{$id} = $intdom;
                   10090:                 }
1.852     albertel 10091: 	    }
                   10092: 	}
                   10093:     }
1.864     albertel 10094:     
                   10095:     sub reset_hosts_info {
1.897     albertel 10096: 	&purge_remembered();
1.864     albertel 10097: 	&reset_domain_info();
                   10098: 	&reset_hosts_ip_info();
1.892     albertel 10099: 	undef(%name_to_host);
1.864     albertel 10100: 	undef(%hostname);
                   10101: 	undef(%hostdom);
                   10102: 	undef(%libserv);
                   10103: 	undef($loaded);
                   10104:     }
1.1       albertel 10105: 
1.852     albertel 10106:     sub load_hosts_tab {
1.869     albertel 10107: 	my ($ignore_cache) = @_;
                   10108: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10109: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10110: 	my @config = <$config>;
                   10111: 	&parse_hosts_tab(\@config);
                   10112: 	close($config);
                   10113: 	$loaded=1;
1.1       albertel 10114:     }
1.852     albertel 10115: 
1.838     albertel 10116:     sub hostname {
1.852     albertel 10117: 	&load_hosts_tab() if (!$loaded);
                   10118: 
1.838     albertel 10119: 	my ($lonid) = @_;
                   10120: 	return $hostname{$lonid};
                   10121:     }
1.845     albertel 10122: 
1.838     albertel 10123:     sub all_hostnames {
1.852     albertel 10124: 	&load_hosts_tab() if (!$loaded);
                   10125: 
1.838     albertel 10126: 	return %hostname;
                   10127:     }
1.845     albertel 10128: 
1.888     albertel 10129:     sub all_names {
                   10130: 	&load_hosts_tab() if (!$loaded);
                   10131: 
                   10132: 	return %name_to_host;
                   10133:     }
                   10134: 
1.974     raeburn  10135:     sub all_host_domain {
                   10136:         &load_hosts_tab() if (!$loaded);
                   10137:         return %hostdom;
                   10138:     }
                   10139: 
1.845     albertel 10140:     sub is_library {
1.852     albertel 10141: 	&load_hosts_tab() if (!$loaded);
                   10142: 
1.845     albertel 10143: 	return exists($libserv{$_[0]});
                   10144:     }
                   10145: 
                   10146:     sub all_library {
1.852     albertel 10147: 	&load_hosts_tab() if (!$loaded);
                   10148: 
1.845     albertel 10149: 	return %libserv;
                   10150:     }
                   10151: 
1.1056.4.2  raeburn  10152:     sub unique_library {
                   10153:         #2x reverse removes all hostnames that appear more than once
                   10154:         my %unique = reverse &all_library();
                   10155:         return reverse %unique;
                   10156:     }
                   10157: 
1.841     albertel 10158:     sub get_servers {
1.852     albertel 10159: 	&load_hosts_tab() if (!$loaded);
                   10160: 
1.841     albertel 10161: 	my ($domain,$type) = @_;
                   10162: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10163: 	                                          : %hostname;
                   10164: 	my %result;
1.842     albertel 10165: 	if (ref($domain) eq 'ARRAY') {
                   10166: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10167: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10168: 		    $result{$host} = $hostname;
                   10169: 		}
                   10170: 	    }
                   10171: 	} else {
                   10172: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10173: 		if ($hostdom{$host} eq $domain) {
                   10174: 		    $result{$host} = $hostname;
                   10175: 		}
1.841     albertel 10176: 	    }
                   10177: 	}
                   10178: 	return %result;
                   10179:     }
1.845     albertel 10180: 
1.1056.4.2  raeburn  10181:     sub get_unique_servers {
                   10182:         my %unique = reverse &get_servers(@_);
                   10183:         return reverse %unique;
                   10184:     }
                   10185: 
1.844     albertel 10186:     sub host_domain {
1.852     albertel 10187: 	&load_hosts_tab() if (!$loaded);
                   10188: 
1.844     albertel 10189: 	my ($lonid) = @_;
                   10190: 	return $hostdom{$lonid};
                   10191:     }
                   10192: 
1.841     albertel 10193:     sub all_domains {
1.852     albertel 10194: 	&load_hosts_tab() if (!$loaded);
                   10195: 
1.841     albertel 10196: 	my %seen;
                   10197: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10198: 	return @uniq;
                   10199:     }
1.1056.4.3  raeburn  10200: 
                   10201:     sub internet_dom {
                   10202:         &load_hosts_tab() if (!$loaded);
                   10203: 
                   10204:         my ($lonid) = @_;
                   10205:         return $internetdom{$lonid};
                   10206:     }
1.1       albertel 10207: }
                   10208: 
1.847     albertel 10209: { 
                   10210:     my %iphost;
1.856     albertel 10211:     my %name_to_ip;
                   10212:     my %lonid_to_ip;
1.869     albertel 10213: 
1.847     albertel 10214:     sub get_hosts_from_ip {
                   10215: 	my ($ip) = @_;
                   10216: 	my %iphosts = &get_iphost();
                   10217: 	if (ref($iphosts{$ip})) {
                   10218: 	    return @{$iphosts{$ip}};
                   10219: 	}
                   10220: 	return;
1.839     albertel 10221:     }
1.864     albertel 10222:     
                   10223:     sub reset_hosts_ip_info {
                   10224: 	undef(%iphost);
                   10225: 	undef(%name_to_ip);
                   10226: 	undef(%lonid_to_ip);
                   10227:     }
1.856     albertel 10228: 
                   10229:     sub get_host_ip {
                   10230: 	my ($lonid) = @_;
                   10231: 	if (exists($lonid_to_ip{$lonid})) {
                   10232: 	    return $lonid_to_ip{$lonid};
                   10233: 	}
                   10234: 	my $name=&hostname($lonid);
                   10235:    	my $ip = gethostbyname($name);
                   10236: 	return if (!$ip || length($ip) ne 4);
                   10237: 	$ip=inet_ntoa($ip);
                   10238: 	$name_to_ip{$name}   = $ip;
                   10239: 	$lonid_to_ip{$lonid} = $ip;
                   10240: 	return $ip;
                   10241:     }
1.847     albertel 10242:     
                   10243:     sub get_iphost {
1.869     albertel 10244: 	my ($ignore_cache) = @_;
1.894     albertel 10245: 
1.869     albertel 10246: 	if (!$ignore_cache) {
                   10247: 	    if (%iphost) {
                   10248: 		return %iphost;
                   10249: 	    }
                   10250: 	    my ($ip_info,$cached)=
                   10251: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10252: 	    if ($cached) {
                   10253: 		%iphost      = %{$ip_info->[0]};
                   10254: 		%name_to_ip  = %{$ip_info->[1]};
                   10255: 		%lonid_to_ip = %{$ip_info->[2]};
                   10256: 		return %iphost;
                   10257: 	    }
                   10258: 	}
1.894     albertel 10259: 
                   10260: 	# get yesterday's info for fallback
                   10261: 	my %old_name_to_ip;
                   10262: 	my ($ip_info,$cached)=
                   10263: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10264: 	if ($cached) {
                   10265: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10266: 	}
                   10267: 
1.888     albertel 10268: 	my %name_to_host = &all_names();
                   10269: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10270: 	    my $ip;
                   10271: 	    if (!exists($name_to_ip{$name})) {
                   10272: 		$ip = gethostbyname($name);
                   10273: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10274: 		    if (defined($old_name_to_ip{$name})) {
                   10275: 			$ip = $old_name_to_ip{$name};
                   10276: 			&logthis("Can't find $name defaulting to old $ip");
                   10277: 		    } else {
                   10278: 			&logthis("Name $name no IP found");
                   10279: 			next;
                   10280: 		    }
                   10281: 		} else {
                   10282: 		    $ip=inet_ntoa($ip);
1.847     albertel 10283: 		}
                   10284: 		$name_to_ip{$name} = $ip;
                   10285: 	    } else {
                   10286: 		$ip = $name_to_ip{$name};
1.653     albertel 10287: 	    }
1.888     albertel 10288: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10289: 		$lonid_to_ip{$id} = $ip;
                   10290: 	    }
                   10291: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10292: 	}
1.869     albertel 10293: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10294: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10295: 				      48*60*60);
1.869     albertel 10296: 
1.847     albertel 10297: 	return %iphost;
1.598     albertel 10298:     }
                   10299: 
1.992     raeburn  10300:     #
                   10301:     #  Given a DNS returns the loncapa host name for that DNS 
                   10302:     # 
                   10303:     sub host_from_dns {
                   10304:         my ($dns) = @_;
                   10305:         my @hosts;
                   10306:         my $ip;
                   10307: 
1.993     raeburn  10308:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10309:             $ip = $name_to_ip{$dns};
                   10310:         }
                   10311:         if (!$ip) {
                   10312:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10313:             if (length($ip) == 4) { 
                   10314: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10315:             }
                   10316:         }
                   10317:         if ($ip) {
                   10318: 	    @hosts = get_hosts_from_ip($ip);
                   10319: 	    return $hosts[0];
                   10320:         }
                   10321:         return undef;
1.986     foxr     10322:     }
1.992     raeburn  10323: 
1.1056.4.3  raeburn  10324:     sub get_internet_names {
                   10325:         my ($lonid) = @_;
                   10326:         return if ($lonid eq '');
                   10327:         my ($idnref,$cached)=
                   10328:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10329:         if ($cached) {
                   10330:             return $idnref;
                   10331:         }
                   10332:         my $ip = &get_host_ip($lonid);
                   10333:         my @hosts = &get_hosts_from_ip($ip);
                   10334:         my %iphost = &get_iphost();
                   10335:         my (@idns,%seen);
                   10336:         foreach my $id (@hosts) {
                   10337:             my $dom = &host_domain($id);
                   10338:             my $prim_id = &domain($dom,'primary');
                   10339:             my $prim_ip = &get_host_ip($prim_id);
                   10340:             next if ($seen{$prim_ip});
                   10341:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10342:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10343:                     my $intdom = &internet_dom($id);
                   10344:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10345:                         push(@idns,$intdom);
                   10346:                     }
                   10347:                 }
                   10348:             }
                   10349:             $seen{$prim_ip} = 1;
                   10350:         }
                   10351:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10352:     }
                   10353: 
                   10354: }
                   10355: 
                   10356: sub all_loncaparevs {
                   10357:     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     10358: }
                   10359: 
1.862     albertel 10360: BEGIN {
                   10361: 
                   10362: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10363:     unless ($readit) {
                   10364: {
                   10365:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10366:     %perlvar = (%perlvar,%{$configvars});
                   10367: }
                   10368: 
                   10369: 
1.1       albertel 10370: # ------------------------------------------------------ Read spare server file
                   10371: {
1.448     albertel 10372:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10373: 
                   10374:     while (my $configline=<$config>) {
                   10375:        chomp($configline);
1.284     matthew  10376:        if ($configline) {
1.784     albertel 10377: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10378: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10379: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10380:        }
                   10381:     }
1.448     albertel 10382:     close($config);
1.1       albertel 10383: }
1.11      www      10384: # ------------------------------------------------------------ Read permissions
                   10385: {
1.448     albertel 10386:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10387: 
                   10388:     while (my $configline=<$config>) {
1.448     albertel 10389: 	chomp($configline);
                   10390: 	if ($configline) {
                   10391: 	    my ($role,$perm)=split(/ /,$configline);
                   10392: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10393: 	}
1.11      www      10394:     }
1.448     albertel 10395:     close($config);
1.11      www      10396: }
                   10397: 
                   10398: # -------------------------------------------- Read plain texts for permissions
                   10399: {
1.448     albertel 10400:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10401: 
                   10402:     while (my $configline=<$config>) {
1.448     albertel 10403: 	chomp($configline);
                   10404: 	if ($configline) {
1.742     raeburn  10405: 	    my ($short,@plain)=split(/:/,$configline);
                   10406:             %{$prp{$short}} = ();
                   10407: 	    if (@plain > 0) {
                   10408:                 $prp{$short}{'std'} = $plain[0];
                   10409:                 for (my $i=1; $i<@plain; $i++) {
                   10410:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10411:                 }
                   10412:             }
1.448     albertel 10413: 	}
1.135     www      10414:     }
1.448     albertel 10415:     close($config);
1.135     www      10416: }
                   10417: 
                   10418: # ---------------------------------------------------------- Read package table
                   10419: {
1.448     albertel 10420:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10421: 
                   10422:     while (my $configline=<$config>) {
1.483     albertel 10423: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10424: 	chomp($configline);
                   10425: 	my ($short,$plain)=split(/:/,$configline);
                   10426: 	my ($pack,$name)=split(/\&/,$short);
                   10427: 	if ($plain ne '') {
                   10428: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10429: 	    $packagetab{$short}=$plain; 
                   10430: 	}
1.11      www      10431:     }
1.448     albertel 10432:     close($config);
1.329     matthew  10433: }
                   10434: 
1.1056.4.3  raeburn  10435: # ---------------------------------------------------------- Read loncaparev table
                   10436: {
                   10437:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10438:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10439:             while (my $configline=<$config>) {
                   10440:                 chomp($configline);
                   10441:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10442:                 $loncaparevs{$hostid}=$loncaparev;
                   10443:             }
                   10444:             close($config);
                   10445:         }
                   10446:     }
                   10447: }
                   10448: 
                   10449: # ---------------------------------------------------------- Read serverhostID table
                   10450: {
                   10451:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10452:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10453:             while (my $configline=<$config>) {
                   10454:                 chomp($configline);
                   10455:                 my ($name,$id)=split(/:/,$configline);
                   10456:                 $serverhomeIDs{$name}=$id;
                   10457:             }
                   10458:             close($config);
                   10459:         }
                   10460:     }
                   10461: }
                   10462: 
1.1056.4.5  raeburn  10463: {
                   10464:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10465:     if (-e $file) {
                   10466:         my $parser = HTML::LCParser->new($file);
                   10467:         while (my $token = $parser->get_token()) {
                   10468:             if ($token->[0] eq 'S') {
                   10469:                 my $item = $token->[1];
                   10470:                 my $name = $token->[2]{'name'};
                   10471:                 my $value = $token->[2]{'value'};
                   10472:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10473:                     my $release = $parser->get_text();
                   10474:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10475:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10476:                 }
                   10477:             }
                   10478:         }
                   10479:     }
                   10480: }
                   10481: 
1.329     matthew  10482: # ------------- set up temporary directory
                   10483: {
                   10484:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10485: 
1.11      www      10486: }
                   10487: 
1.794     albertel 10488: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10489: 				'compress_threshold'=> 20_000,
                   10490:  			        });
1.185     www      10491: 
1.281     www      10492: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10493: $dumpcount=0;
1.958     www      10494: $locknum=0;
1.22      www      10495: 
1.163     harris41 10496: &logtouch();
1.672     albertel 10497: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10498: $readit=1;
1.564     albertel 10499:     {
                   10500: 	use integer;
                   10501: 	my $test=(2**32)+1;
1.568     albertel 10502: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10503: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10504:     }
1.195     www      10505: }
1.1       albertel 10506: }
1.179     www      10507: 
1.1       albertel 10508: 1;
1.191     harris41 10509: __END__
                   10510: 
1.243     albertel 10511: =pod
                   10512: 
1.191     harris41 10513: =head1 NAME
                   10514: 
1.243     albertel 10515: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10516: 
                   10517: =head1 SYNOPSIS
                   10518: 
1.243     albertel 10519: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10520: 
                   10521:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10522: 
1.243     albertel 10523: Common parameters:
                   10524: 
                   10525: =over 4
                   10526: 
                   10527: =item *
                   10528: 
                   10529: $uname : an internal username (if $cname expecting a course Id specifically)
                   10530: 
                   10531: =item *
                   10532: 
                   10533: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10534: 
                   10535: =item *
                   10536: 
                   10537: $symb : a resource instance identifier
                   10538: 
                   10539: =item *
                   10540: 
                   10541: $namespace : the name of a .db file that contains the data needed or
                   10542: being set.
                   10543: 
                   10544: =back
                   10545: 
1.394     bowersj2 10546: =head1 OVERVIEW
1.191     harris41 10547: 
1.394     bowersj2 10548: lonnet provides subroutines which interact with the
                   10549: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10550: about classes, users, and resources.
1.243     albertel 10551: 
                   10552: For many of these objects you can also use this to store data about
                   10553: them or modify them in various ways.
1.191     harris41 10554: 
1.394     bowersj2 10555: =head2 Symbs
1.191     harris41 10556: 
1.394     bowersj2 10557: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10558: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10559: map, the resource number of the resource in the map, and the URL of
                   10560: the resource itself. The latter is somewhat redundant, but might help
                   10561: if maps change.
                   10562: 
                   10563: An example is
                   10564: 
                   10565:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10566: 
                   10567: The respective map entry is
                   10568: 
                   10569:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10570:   title="Problem 2">
                   10571:  </resource>
                   10572: 
                   10573: Symbs are used by the random number generator, as well as to store and
                   10574: restore data specific to a certain instance of for example a problem.
                   10575: 
                   10576: =head2 Storing And Retrieving Data
                   10577: 
                   10578: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10579: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10580: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10581: is is the non-critical message twin of cstore. These functions are for
                   10582: handlers to store a perl hash to a user's permanent data space in an
                   10583: easy manner, and to retrieve it again on another call. It is expected
                   10584: that a handler would use this once at the beginning to retrieve data,
                   10585: and then again once at the end to send only the new data back.
                   10586: 
                   10587: The data is stored in the user's data directory on the user's
                   10588: homeserver under the ID of the course.
                   10589: 
                   10590: The hash that is returned by restore will have all of the previous
                   10591: value for all of the elements of the hash.
                   10592: 
                   10593: Example:
                   10594: 
                   10595:  #creating a hash
                   10596:  my %hash;
                   10597:  $hash{'foo'}='bar';
                   10598: 
                   10599:  #storing it
                   10600:  &Apache::lonnet::cstore(\%hash);
                   10601: 
                   10602:  #changing a value
                   10603:  $hash{'foo'}='notbar';
                   10604: 
                   10605:  #adding a new value
                   10606:  $hash{'bar'}='foo';
                   10607:  &Apache::lonnet::cstore(\%hash);
                   10608: 
                   10609:  #retrieving the hash
                   10610:  my %history=&Apache::lonnet::restore();
                   10611: 
                   10612:  #print the hash
                   10613:  foreach my $key (sort(keys(%history))) {
                   10614:    print("\%history{$key} = $history{$key}");
                   10615:  }
                   10616: 
                   10617: Will print out:
1.191     harris41 10618: 
1.394     bowersj2 10619:  %history{1:foo} = bar
                   10620:  %history{1:keys} = foo:timestamp
                   10621:  %history{1:timestamp} = 990455579
                   10622:  %history{2:bar} = foo
                   10623:  %history{2:foo} = notbar
                   10624:  %history{2:keys} = foo:bar:timestamp
                   10625:  %history{2:timestamp} = 990455580
                   10626:  %history{bar} = foo
                   10627:  %history{foo} = notbar
                   10628:  %history{timestamp} = 990455580
                   10629:  %history{version} = 2
                   10630: 
                   10631: Note that the special hash entries C<keys>, C<version> and
                   10632: C<timestamp> were added to the hash. C<version> will be equal to the
                   10633: total number of versions of the data that have been stored. The
                   10634: C<timestamp> attribute will be the UNIX time the hash was
                   10635: stored. C<keys> is available in every historical section to list which
                   10636: keys were added or changed at a specific historical revision of a
                   10637: hash.
                   10638: 
                   10639: B<Warning>: do not store the hash that restore returns directly. This
                   10640: will cause a mess since it will restore the historical keys as if the
                   10641: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10642: 
1.394     bowersj2 10643: Calling convention:
1.191     harris41 10644: 
1.394     bowersj2 10645:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10646:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10647: 
1.394     bowersj2 10648: For more detailed information, see lonnet specific documentation.
1.191     harris41 10649: 
1.394     bowersj2 10650: =head1 RETURN MESSAGES
1.191     harris41 10651: 
1.394     bowersj2 10652: =over 4
1.191     harris41 10653: 
1.394     bowersj2 10654: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10655: 
1.394     bowersj2 10656: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10657: when the connection is brought back up
1.191     harris41 10658: 
1.394     bowersj2 10659: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10660: for later delivery
1.191     harris41 10661: 
1.967     bisitz   10662: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10663: 
1.394     bowersj2 10664: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10665: that was requested
1.191     harris41 10666: 
1.243     albertel 10667: =back
1.191     harris41 10668: 
1.243     albertel 10669: =head1 PUBLIC SUBROUTINES
1.191     harris41 10670: 
1.243     albertel 10671: =head2 Session Environment Functions
1.191     harris41 10672: 
1.243     albertel 10673: =over 4
1.191     harris41 10674: 
1.394     bowersj2 10675: =item * 
                   10676: X<appenv()>
1.949     raeburn  10677: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10678: the user envirnoment file, and will be restored for each access this
1.620     albertel 10679: user makes during this session, also modifies the %env for the current
1.949     raeburn  10680: process. Optional rolesarrayref - if defined contains a reference to an array
                   10681: of roles which are exempt from the restriction on modifying user.role entries 
                   10682: in the user's environment.db and in %env.    
1.191     harris41 10683: 
                   10684: =item *
1.394     bowersj2 10685: X<delenv()>
1.987     raeburn  10686: B<delenv($delthis,$regexp)>: removes all items from the session
                   10687: environment file that begin with $delthis. If the 
                   10688: optional second arg - $regexp - is true, $delthis is treated as a 
                   10689: regular expression, otherwise \Q$delthis\E is used. 
                   10690: The values are also deleted from the current processes %env.
1.191     harris41 10691: 
1.795     albertel 10692: =item * get_env_multiple($name) 
                   10693: 
                   10694: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10695: values may be defined and end up as an array ref.
                   10696: 
                   10697: returns an array of values
                   10698: 
1.243     albertel 10699: =back
                   10700: 
                   10701: =head2 User Information
1.191     harris41 10702: 
1.243     albertel 10703: =over 4
1.191     harris41 10704: 
                   10705: =item *
1.394     bowersj2 10706: X<queryauthenticate()>
                   10707: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10708: authentication scheme
                   10709: 
                   10710: =item *
1.394     bowersj2 10711: X<authenticate()>
1.1056.4.3  raeburn  10712: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10713: authenticate user from domain's lib servers (first use the current
                   10714: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10715: $checkdefauth is optional (value is 1 if a check should be made to
                   10716:    authenticate user using default authentication method, and allow
                   10717:    account creation if username does not have account in the domain).
                   10718: $clientcancheckhost is optional (value is 1 if checking whether the
                   10719:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10720: 
                   10721: =item *
1.394     bowersj2 10722: X<homeserver()>
                   10723: B<homeserver($uname,$udom)>: find the server which has
                   10724: the user's directory and files (there must be only one), this caches
                   10725: the answer, and also caches if there is a borken connection.
1.191     harris41 10726: 
                   10727: =item *
1.394     bowersj2 10728: X<idget()>
                   10729: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10730: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10731: username, and only 1 username per ID in a specific domain) (returns
                   10732: hash: id=>name,id=>name)
1.191     harris41 10733: 
                   10734: =item *
1.394     bowersj2 10735: X<idrget()>
                   10736: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10737: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10738: 
                   10739: =item *
1.394     bowersj2 10740: X<idput()>
                   10741: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10742: 
                   10743: =item *
1.394     bowersj2 10744: X<rolesinit()>
                   10745: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10746: 
                   10747: =item *
1.551     albertel 10748: X<getsection()>
                   10749: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10750: course $cname, return section name/number or '' for "not in course"
                   10751: and '-1' for "no section"
                   10752: 
                   10753: =item *
1.394     bowersj2 10754: X<userenvironment()>
                   10755: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10756: passed in @what from the requested user's environment, returns a hash
                   10757: 
1.858     raeburn  10758: =item * 
                   10759: X<userlog_query()>
1.859     albertel 10760: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10761: activity.log file. %filters defines filters applied when parsing the
                   10762: log file. These can be start or end timestamps, or the type of action
                   10763: - log to look for Login or Logout events, check for Checkin or
                   10764: Checkout, role for role selection. The response is in the form
                   10765: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10766: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10767: 
1.243     albertel 10768: =back
                   10769: 
                   10770: =head2 User Roles
                   10771: 
                   10772: =over 4
                   10773: 
                   10774: =item *
                   10775: 
1.810     raeburn  10776: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10777:  F: full access
                   10778:  U,I,K: authentication modes (cxx only)
                   10779:  '': forbidden
                   10780:  1: user needs to choose course
                   10781:  2: browse allowed
1.766     albertel 10782:  A: passphrase authentication needed
1.243     albertel 10783: 
                   10784: =item *
                   10785: 
                   10786: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10787: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10788: and course level
                   10789: 
                   10790: =item *
                   10791: 
1.988     raeburn  10792: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10793: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10794: $type is Course (default) or Community.
1.988     raeburn  10795: If $forcedefault evaluates to true, text returned will be default 
                   10796: text for $type. Otherwise, if this is a course, the text returned 
                   10797: will be a custom name for the role (if defined in the course's 
                   10798: environment).  If no custom name is defined the default is returned.
                   10799:    
1.832     raeburn  10800: =item *
                   10801: 
1.935     raeburn  10802: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10803: All arguments are optional. Returns a hash of a roles, either for
                   10804: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10805: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10806: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10807: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10808: For each key, value is set to colon-separated start and end times for
                   10809: the role.  If no username and domain are specified, will default to
1.934     raeburn  10810: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10811: of role statuses (active, future or previous), roles 
                   10812: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10813: to restrict the list of roles reported. If no array ref is 
                   10814: provided for types, will default to return only active roles.
1.834     albertel 10815: 
1.243     albertel 10816: =back
                   10817: 
                   10818: =head2 User Modification
                   10819: 
                   10820: =over 4
                   10821: 
                   10822: =item *
                   10823: 
1.957     raeburn  10824: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10825: user for the level given by URL.  Optional start and end dates (leave empty
                   10826: string or zero for "no date")
1.191     harris41 10827: 
                   10828: =item *
                   10829: 
1.243     albertel 10830: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10831: change a users, password, possible return values are: ok,
                   10832: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10833: refused
1.191     harris41 10834: 
                   10835: =item *
                   10836: 
1.243     albertel 10837: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10838: 
                   10839: =item *
                   10840: 
1.1056.4.1  raeburn  10841: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10842:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10843: 
                   10844: will update user information (firstname,middlename,lastname,generation,
                   10845: permanentemail), and if forceid is true, student/employee ID also.
                   10846: A user's institutional affiliation(s) can also be updated.
                   10847: User information fields will not be overwritten with empty entries 
                   10848: unless the field is included in the $candelete array reference.
                   10849: This array is included when a single user is modified via "Manage Users",
                   10850: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10851: 
                   10852: =item *
                   10853: 
1.286     matthew  10854: modifystudent
                   10855: 
1.957     raeburn  10856: modify a student's enrollment and identification information.
1.286     matthew  10857: The course id is resolved based on the current users environment.  
                   10858: This means the envoking user must be a course coordinator or otherwise
                   10859: associated with a course.
                   10860: 
1.297     matthew  10861: This call is essentially a wrapper for lonnet::modifyuser and
                   10862: lonnet::modify_student_enrollment
1.286     matthew  10863: 
                   10864: Inputs: 
                   10865: 
                   10866: =over 4
                   10867: 
1.957     raeburn  10868: =item B<$udom> Student's loncapa domain
1.286     matthew  10869: 
1.957     raeburn  10870: =item B<$uname> Student's loncapa login name
1.286     matthew  10871: 
1.964     bisitz   10872: =item B<$uid> Student/Employee ID
1.286     matthew  10873: 
1.957     raeburn  10874: =item B<$umode> Student's authentication mode
1.286     matthew  10875: 
1.957     raeburn  10876: =item B<$upass> Student's password
1.286     matthew  10877: 
1.957     raeburn  10878: =item B<$first> Student's first name
1.286     matthew  10879: 
1.957     raeburn  10880: =item B<$middle> Student's middle name
1.286     matthew  10881: 
1.957     raeburn  10882: =item B<$last> Student's last name
1.286     matthew  10883: 
1.957     raeburn  10884: =item B<$gene> Student's generation
1.286     matthew  10885: 
1.957     raeburn  10886: =item B<$usec> Student's section in course
1.286     matthew  10887: 
                   10888: =item B<$end> Unix time of the roles expiration
                   10889: 
                   10890: =item B<$start> Unix time of the roles start date
                   10891: 
                   10892: =item B<$forceid> If defined, allow $uid to be changed
                   10893: 
                   10894: =item B<$desiredhome> server to use as home server for student
                   10895: 
1.957     raeburn  10896: =item B<$email> Student's permanent e-mail address
                   10897: 
                   10898: =item B<$type> Type of enrollment (auto or manual)
                   10899: 
1.963     raeburn  10900: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10901: 
                   10902: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10903: 
1.963     raeburn  10904: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10905: 
1.963     raeburn  10906: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10907: 
1.963     raeburn  10908: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10909: 
1.286     matthew  10910: =back
1.297     matthew  10911: 
                   10912: =item *
                   10913: 
                   10914: modify_student_enrollment
                   10915: 
                   10916: Change a students enrollment status in a class.  The environment variable
                   10917: 'role.request.course' must be defined for this function to proceed.
                   10918: 
                   10919: Inputs:
                   10920: 
                   10921: =over 4
                   10922: 
                   10923: =item $udom, students domain
                   10924: 
                   10925: =item $uname, students name
                   10926: 
                   10927: =item $uid, students user id
                   10928: 
                   10929: =item $first, students first name
                   10930: 
                   10931: =item $middle
                   10932: 
                   10933: =item $last
                   10934: 
                   10935: =item $gene
                   10936: 
                   10937: =item $usec
                   10938: 
                   10939: =item $end
                   10940: 
                   10941: =item $start
                   10942: 
1.957     raeburn  10943: =item $type
                   10944: 
                   10945: =item $locktype
                   10946: 
                   10947: =item $cid
                   10948: 
                   10949: =item $selfenroll
                   10950: 
                   10951: =item $context
                   10952: 
1.297     matthew  10953: =back
                   10954: 
1.191     harris41 10955: 
                   10956: =item *
                   10957: 
1.243     albertel 10958: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10959: custom role; give a custom role to a user for the level given by URL.  Specify
                   10960: name and domain of role author, and role name
1.191     harris41 10961: 
                   10962: =item *
                   10963: 
1.243     albertel 10964: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10965: 
                   10966: =item *
                   10967: 
1.243     albertel 10968: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10969: 
                   10970: =back
                   10971: 
                   10972: =head2 Course Infomation
                   10973: 
                   10974: =over 4
1.191     harris41 10975: 
                   10976: =item *
                   10977: 
1.631     albertel 10978: coursedescription($courseid) : returns a hash of information about the
                   10979: specified course id, including all environment settings for the
                   10980: course, the description of the course will be in the hash under the
                   10981: key 'description'
1.191     harris41 10982: 
                   10983: =item *
                   10984: 
1.624     albertel 10985: resdata($name,$domain,$type,@which) : request for current parameter
                   10986: setting for a specific $type, where $type is either 'course' or 'user',
                   10987: @what should be a list of parameters to ask about. This routine caches
                   10988: answers for 5 minutes.
1.243     albertel 10989: 
1.877     foxr     10990: =item *
                   10991: 
                   10992: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10993: data base, returning a hash that is keyed by the resource name and has
                   10994: values that are the resource value.  I believe that the timestamps and
                   10995: versions are also returned.
                   10996: 
                   10997: 
1.243     albertel 10998: =back
                   10999: 
                   11000: =head2 Course Modification
                   11001: 
                   11002: =over 4
1.191     harris41 11003: 
                   11004: =item *
                   11005: 
1.243     albertel 11006: writecoursepref($courseid,%prefs) : write preferences (environment
                   11007: database) for a course
1.191     harris41 11008: 
                   11009: =item *
                   11010: 
1.1011    raeburn  11011: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11012: 
                   11013: =item *
                   11014: 
1.1038    raeburn  11015: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11016: 
                   11017: =back
                   11018: 
                   11019: =head2 Resource Subroutines
                   11020: 
                   11021: =over 4
1.191     harris41 11022: 
                   11023: =item *
                   11024: 
1.243     albertel 11025: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11026: 
                   11027: =item *
                   11028: 
1.243     albertel 11029: repcopy($filename) : subscribes to the requested file, and attempts to
                   11030: replicate from the owning library server, Might return
1.607     raeburn  11031: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11032: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11033: resource. Expects the local filesystem pathname
                   11034: (/home/httpd/html/res/....)
                   11035: 
                   11036: =back
                   11037: 
                   11038: =head2 Resource Information
                   11039: 
                   11040: =over 4
1.191     harris41 11041: 
                   11042: =item *
                   11043: 
1.243     albertel 11044: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11045: a vairety of different possible values, $varname should be a request
                   11046: string, and the other parameters can be used to specify who and what
                   11047: one is asking about.
                   11048: 
                   11049: Possible values for $varname are environment.lastname (or other item
                   11050: from the envirnment hash), user.name (or someother aspect about the
                   11051: user), resource.0.maxtries (or some other part and parameter of a
                   11052: resource)
1.204     albertel 11053: 
                   11054: =item *
                   11055: 
1.243     albertel 11056: directcondval($number) : get current value of a condition; reads from a state
                   11057: string
1.204     albertel 11058: 
                   11059: =item *
                   11060: 
1.243     albertel 11061: condval($condidx) : value of condition index based on state
1.204     albertel 11062: 
                   11063: =item *
                   11064: 
1.243     albertel 11065: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11066: resource's metadata, $what should be either a specific key, or either
                   11067: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11068: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11069: 
                   11070: this function automatically caches all requests
1.191     harris41 11071: 
                   11072: =item *
                   11073: 
1.243     albertel 11074: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11075: network of library servers; returns file handle of where SQL and regex results
                   11076: will be stored for query
1.191     harris41 11077: 
                   11078: =item *
                   11079: 
1.243     albertel 11080: symbread($filename) : return symbolic list entry (filename argument optional);
                   11081: returns the data handle
1.191     harris41 11082: 
                   11083: =item *
                   11084: 
1.243     albertel 11085: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11086: a possible symb for the URL in $thisfn, and if is an encryypted
                   11087: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11088: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11089: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11090: 
1.191     harris41 11091: 
                   11092: =item *
                   11093: 
1.243     albertel 11094: symbclean($symb) : removes versions numbers from a symb, returns the
                   11095: cleaned symb
1.191     harris41 11096: 
                   11097: =item *
                   11098: 
1.243     albertel 11099: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11100: course map, user must be in a course for it to work.
1.191     harris41 11101: 
                   11102: =item *
                   11103: 
1.243     albertel 11104: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11105: 
                   11106: =item *
                   11107: 
1.243     albertel 11108: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11109: a random seed, all arguments are optional, if they aren't sent it uses the
                   11110: environment to derive them. Note: if symb isn't sent and it can't get one
                   11111: from &symbread it will use the current time as its return value
1.191     harris41 11112: 
                   11113: =item *
                   11114: 
1.243     albertel 11115: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11116: unfakeable, receipt
1.191     harris41 11117: 
                   11118: =item *
                   11119: 
1.620     albertel 11120: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11121: 
                   11122: =item *
                   11123: 
1.243     albertel 11124: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11125: 
                   11126: =item *
                   11127: 
1.243     albertel 11128: 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 11129: 
                   11130: =item *
                   11131: 
1.243     albertel 11132: 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 11133: 
                   11134: =item *
                   11135: 
1.243     albertel 11136: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11137: 
                   11138: =item *
                   11139: 
1.243     albertel 11140: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11141: forcing spreadsheet to reevaluate the resource scores next time.
                   11142: 
                   11143: =back
                   11144: 
                   11145: =head2 Storing/Retreiving Data
                   11146: 
                   11147: =over 4
1.191     harris41 11148: 
                   11149: =item *
                   11150: 
1.243     albertel 11151: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11152: for this url; hashref needs to be given and should be a \%hashname; the
                   11153: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11154: be derived from the env
1.191     harris41 11155: 
                   11156: =item *
                   11157: 
1.243     albertel 11158: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11159: uses critical subroutine
1.191     harris41 11160: 
                   11161: =item *
                   11162: 
1.243     albertel 11163: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11164: all args are optional
1.191     harris41 11165: 
                   11166: =item *
                   11167: 
1.717     albertel 11168: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11169: dumps the complete (or key matching regexp) namespace into a hash
                   11170: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11171: normally &store()ed into
                   11172: 
                   11173: $range should be either an integer '100' (give me the first 100
                   11174:                                            matching records)
                   11175:               or be  two integers sperated by a - with no spaces
                   11176:                  '30-50' (give me the 30th through the 50th matching
                   11177:                           records)
                   11178: 
                   11179: 
                   11180: =item *
                   11181: 
                   11182: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11183: replaces a &store() version of data with a replacement set of data
                   11184: for a particular resource in a namespace passed in the $storehash hash 
                   11185: reference
                   11186: 
                   11187: =item *
                   11188: 
1.243     albertel 11189: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11190: works very similar to store/cstore, but all data is stored in a
                   11191: temporary location and can be reset using tmpreset, $storehash should
                   11192: be a hash reference, returns nothing on success
1.191     harris41 11193: 
                   11194: =item *
                   11195: 
1.243     albertel 11196: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11197: similar to restore, but all data is stored in a temporary location and
                   11198: can be reset using tmpreset. Returns a hash of values on success,
                   11199: error string otherwise.
1.191     harris41 11200: 
                   11201: =item *
                   11202: 
1.243     albertel 11203: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11204: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11205: 
                   11206: =item *
                   11207: 
1.243     albertel 11208: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11209: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11210: 
                   11211: =item *
                   11212: 
1.243     albertel 11213: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11214: namesp ($udom and $uname are optional)
1.191     harris41 11215: 
                   11216: =item *
                   11217: 
1.702     albertel 11218: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11219: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11220: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11221: 
1.702     albertel 11222: $range should be either an integer '100' (give me the first 100
                   11223:                                            matching records)
                   11224:               or be  two integers sperated by a - with no spaces
                   11225:                  '30-50' (give me the 30th through the 50th matching
                   11226:                           records)
1.449     matthew  11227: =item *
                   11228: 
                   11229: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11230: $store can be a scalar, an array reference, or if the amount to be 
                   11231: incremented is > 1, a hash reference.
                   11232: 
                   11233: ($udom and $uname are optional)
1.191     harris41 11234: 
                   11235: =item *
                   11236: 
1.243     albertel 11237: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11238: ($udom and $uname are optional)
1.191     harris41 11239: 
                   11240: =item *
                   11241: 
1.243     albertel 11242: cput($namespace,$storehash,$udom,$uname) : critical put
                   11243: ($udom and $uname are optional)
1.191     harris41 11244: 
                   11245: =item *
                   11246: 
1.748     albertel 11247: newput($namespace,$storehash,$udom,$uname) :
                   11248: 
                   11249: Attempts to store the items in the $storehash, but only if they don't
                   11250: currently exist, if this succeeds you can be certain that you have 
                   11251: successfully created a new key value pair in the $namespace db.
                   11252: 
                   11253: 
                   11254: Args:
                   11255:  $namespace: name of database to store values to
                   11256:  $storehash: hashref to store to the db
                   11257:  $udom: (optional) domain of user containing the db
                   11258:  $uname: (optional) name of user caontaining the db
                   11259: 
                   11260: Returns:
                   11261:  'ok' -> succeeded in storing all keys of $storehash
                   11262:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11263:                         least <key> already existed in the db (other
                   11264:                         requested keys may also already exist)
1.967     bisitz   11265:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11266:  'con_lost' -> unable to contact request server
                   11267:  'refused' -> action was not allowed by remote machine
                   11268: 
                   11269: 
                   11270: =item *
                   11271: 
1.243     albertel 11272: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11273: reference filled in from namesp (encrypts the return communication)
                   11274: ($udom and $uname are optional)
1.191     harris41 11275: 
                   11276: =item *
                   11277: 
1.243     albertel 11278: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11279: critical subroutine
                   11280: 
1.806     raeburn  11281: =item *
                   11282: 
1.860     raeburn  11283: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11284: array reference filled in from namespace found in domain level on either
                   11285: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11286: 
                   11287: =item *
                   11288: 
1.860     raeburn  11289: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11290: domain level either on specified domain server ($uhome) or primary domain 
                   11291: server ($udom and $uhome are optional)
1.806     raeburn  11292: 
1.943     raeburn  11293: =item * 
                   11294: 
                   11295: get_domain_defaults($target_domain) : returns hash with defaults for
                   11296: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11297: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11298: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11299: Values are retrieved from cache (if current), or from domain's configuration.db
                   11300: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11301: or lonTabs/domain.tab. 
                   11302: 
                   11303: %domdefaults = &get_auth_defaults($target_domain);
                   11304: 
1.243     albertel 11305: =back
                   11306: 
                   11307: =head2 Network Status Functions
                   11308: 
                   11309: =over 4
1.191     harris41 11310: 
                   11311: =item *
                   11312: 
                   11313: dirlist($uri) : return directory list based on URI
                   11314: 
                   11315: =item *
                   11316: 
1.243     albertel 11317: spareserver() : find server with least workload from spare.tab
                   11318: 
1.986     foxr     11319: 
                   11320: =item *
                   11321: 
                   11322: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11323: if there is no corresponding loncapa host.
                   11324: 
1.243     albertel 11325: =back
                   11326: 
1.986     foxr     11327: 
1.243     albertel 11328: =head2 Apache Request
                   11329: 
                   11330: =over 4
1.191     harris41 11331: 
                   11332: =item *
                   11333: 
1.243     albertel 11334: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11335: localhost, posts hash
                   11336: 
                   11337: =back
                   11338: 
                   11339: =head2 Data to String to Data
                   11340: 
                   11341: =over 4
1.191     harris41 11342: 
                   11343: =item *
                   11344: 
1.243     albertel 11345: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11346: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11347: 
                   11348: =item *
                   11349: 
1.243     albertel 11350: hashref2str($hashref) : convert a hashref into a string complete with
                   11351: escaping and '=' and '&' separators, supports elements that are
                   11352: arrayrefs and hashrefs
1.191     harris41 11353: 
                   11354: =item *
                   11355: 
1.243     albertel 11356: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11357: with escaping and '&' separators, supports elements that are arrayrefs
                   11358: and hashrefs
1.191     harris41 11359: 
                   11360: =item *
                   11361: 
1.243     albertel 11362: str2hash($string) : convert string to hash using unescaping and
                   11363: splitting on '=' and '&', supports elements that are arrayrefs and
                   11364: hashrefs
1.191     harris41 11365: 
                   11366: =item *
                   11367: 
1.243     albertel 11368: str2array($string) : convert string to hash using unescaping and
                   11369: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11370: 
                   11371: =back
                   11372: 
                   11373: =head2 Logging Routines
                   11374: 
                   11375: =over 4
                   11376: 
                   11377: These routines allow one to make log messages in the lonnet.log and
                   11378: lonnet.perm logfiles.
1.191     harris41 11379: 
                   11380: =item *
                   11381: 
1.243     albertel 11382: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11383: 
                   11384: =item *
                   11385: 
1.243     albertel 11386: logthis() : append message to the normal lonnet.log file, it gets
                   11387: preiodically rolled over and deleted.
1.191     harris41 11388: 
                   11389: =item *
                   11390: 
1.243     albertel 11391: logperm() : append a permanent message to lonnet.perm.log, this log
                   11392: file never gets deleted by any automated portion of the system, only
                   11393: messages of critical importance should go in here.
                   11394: 
                   11395: =back
                   11396: 
                   11397: =head2 General File Helper Routines
                   11398: 
                   11399: =over 4
1.191     harris41 11400: 
                   11401: =item *
                   11402: 
1.481     raeburn  11403: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11404: (a) files in /uploaded
                   11405:   (i) If a local copy of the file exists - 
                   11406:       compares modification date of local copy with last-modified date for 
                   11407:       definitive version stored on home server for course. If local copy is 
                   11408:       stale, requests a new version from the home server and stores it. 
                   11409:       If the original has been removed from the home server, then local copy 
                   11410:       is unlinked.
                   11411:   (ii) If local copy does not exist -
                   11412:       requests the file from the home server and stores it. 
                   11413:   
                   11414:   If $caller is 'uploadrep':  
                   11415:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11416:     for request for files originally uploaded via DOCS. 
                   11417:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11418:   
                   11419:   Otherwise:
                   11420:      This indicates a call from the content generation phase of the request.
                   11421:      -  returns the entire contents of the file or -1.
                   11422:      
                   11423: (b) files in /res
                   11424:    - returns the entire contents of a file or -1; 
                   11425:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11426: 
1.712     albertel 11427: 
                   11428: =item *
                   11429: 
                   11430: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11431:                   reference
                   11432: 
                   11433: returns either a stat() list of data about the file or an empty list
                   11434: if the file doesn't exist or couldn't find out about it (connection
                   11435: problems or user unknown)
                   11436: 
1.191     harris41 11437: =item *
                   11438: 
1.243     albertel 11439: filelocation($dir,$file) : returns file system location of a file
                   11440: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11441: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11442: and a file of ../bob will become /a/bob)
1.191     harris41 11443: 
                   11444: =item *
                   11445: 
                   11446: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11447: filelocation except for hrefs
                   11448: 
                   11449: =item *
                   11450: 
                   11451: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11452: 
1.243     albertel 11453: =back
                   11454: 
1.608     albertel 11455: =head2 Usererfile file routines (/uploaded*)
                   11456: 
                   11457: =over 4
                   11458: 
                   11459: =item *
                   11460: 
                   11461: userfileupload(): main rotine for putting a file in a user or course's
                   11462:                   filespace, arguments are,
                   11463: 
1.620     albertel 11464:  formname - required - this is the name of the element in $env where the
1.608     albertel 11465:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11466:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11467:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11468:  context - if coursedoc, store the file in the course of the active role
                   11469:              of the current user;
                   11470:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11471:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11472:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11473:          if undefined, it will be placed in "unknown"
                   11474: 
                   11475:  (This routine calls clean_filename() to remove any dangerous
                   11476:  characters from the filename, and then calls finuserfileupload() to
                   11477:  complete the transaction)
                   11478: 
                   11479:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11480:  and /adm/notfound.html if unsuccessful
                   11481: 
                   11482: =item *
                   11483: 
                   11484: clean_filename(): routine for cleaing a filename up for storage in
                   11485:                  userfile space, argument is:
                   11486: 
                   11487:  filename - proposed filename
                   11488: 
                   11489: returns: the new clean filename
                   11490: 
                   11491: =item *
                   11492: 
1.1056.4.13  raeburn  11493: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11494: userspace, probably shouldn't be called directly
                   11495: 
                   11496:   docuname: username or courseid of destination for the file
                   11497:   docudom: domain of user/course of destination for the file
                   11498:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11499:   fname: filename (including subdirectories) for the file
                   11500:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11501:   allfiles: reference to hash used to store objects found by parser
                   11502:   codebase: reference to hash used for codebases of java objects found by parser
                   11503:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11504:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11505:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11506:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11507:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11508:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16  raeburn  11509:   mimetype: reference to scalar to accommodate mime type determined
                   11510:             from File::MMagic if $parser = parse.
1.608     albertel 11511: 
                   11512:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11513:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11514:  was 'overwrite').
                   11515: 
1.608     albertel 11516: 
                   11517: =item *
                   11518: 
                   11519: renameuserfile(): renames an existing userfile to a new name
                   11520: 
                   11521:   Args:
                   11522:    docuname: username or courseid of destination for the file
                   11523:    docudom: domain of user/course of destination for the file
                   11524:    old: current file name (including any subdirs under userfiles)
                   11525:    new: desired file name (including any subdirs under userfiles)
                   11526: 
                   11527: =item *
                   11528: 
                   11529: mkdiruserfile(): creates a directory is a userfiles dir
                   11530: 
                   11531:   Args:
                   11532:    docuname: username or courseid of destination for the file
                   11533:    docudom: domain of user/course of destination for the file
                   11534:    dir: dir to create (including any subdirs under userfiles)
                   11535: 
                   11536: =item *
                   11537: 
                   11538: removeuserfile(): removes a file that exists in userfiles
                   11539: 
                   11540:   Args:
                   11541:    docuname: username or courseid of destination for the file
                   11542:    docudom: domain of user/course of destination for the file
                   11543:    fname: filname to delete (including any subdirs under userfiles)
                   11544: 
                   11545: =item *
                   11546: 
                   11547: removeuploadedurl(): convience function for removeuserfile()
                   11548: 
                   11549:   Args:
                   11550:    url:  a full /uploaded/... url to delete
                   11551: 
1.747     albertel 11552: =item * 
                   11553: 
                   11554: get_portfile_permissions():
                   11555:   Args:
                   11556:     domain: domain of user or course contain the portfolio files
                   11557:     user: name of user or num of course contain the portfolio files
                   11558:   Returns:
                   11559:     hashref of a dump of the proper file_permissions.db
                   11560:    
                   11561: 
                   11562: =item * 
                   11563: 
                   11564: get_access_controls():
                   11565: 
                   11566: Args:
                   11567:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11568:   group: (optional) the group you want the files associated with
                   11569:   file: (optional) the file you want access info on
                   11570: 
                   11571: Returns:
1.749     raeburn  11572:     a hash (keys are file names) of hashes containing
                   11573:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11574:         values are XML containing access control settings (see below) 
1.747     albertel 11575: 
                   11576: Internal notes:
                   11577: 
1.749     raeburn  11578:  access controls are stored in file_permissions.db as key=value pairs.
                   11579:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11580:         where scope -> public,guest,course,group,domains or users.
                   11581:               end -> UNIX time for end of access (0 -> no end date)
                   11582:               start -> UNIX time for start of access
                   11583: 
                   11584:     value -> XML description of access control
                   11585:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11586:             <start></start>
                   11587:             <end></end>
                   11588: 
                   11589:             <password></password>  for scope type = guest
                   11590: 
                   11591:             <domain></domain>     for scope type = course or group
                   11592:             <number></number>
                   11593:             <roles id="">
                   11594:              <role></role>
                   11595:              <access></access>
                   11596:              <section></section>
                   11597:              <group></group>
                   11598:             </roles>
                   11599: 
                   11600:             <dom></dom>         for scope type = domains
                   11601: 
                   11602:             <users>             for scope type = users
                   11603:              <user>
                   11604:               <uname></uname>
                   11605:               <udom></udom>
                   11606:              </user>
                   11607:             </users>
                   11608:            </scope> 
                   11609:               
                   11610:  Access data is also aggregated for each file in an additional key=value pair:
                   11611:  key -> path to file/file_name\0accesscontrol 
                   11612:  value -> reference to hash
                   11613:           hash contains key = value pairs
                   11614:           where key = uniqueID:scope_end_start
                   11615:                 value = UNIX time record was last updated
                   11616: 
                   11617:           Used to improve speed of look-ups of access controls for each file.  
                   11618:  
                   11619:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11620: 
                   11621: modify_access_controls():
                   11622: 
                   11623: Modifies access controls for a portfolio file
                   11624: Args
                   11625: 1. file name
                   11626: 2. reference to hash of required changes,
                   11627: 3. domain
                   11628: 4. username
                   11629:   where domain,username are the domain of the portfolio owner 
                   11630:   (either a user or a course) 
                   11631: 
                   11632: Returns:
                   11633: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11634: 2. result of deletions ('ok' or 'error', with error message).
                   11635: 3. reference to hash of any new or updated access controls.
                   11636: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11637:    key = integer (inbound ID)
                   11638:    value = uniqueID  
1.747     albertel 11639: 
1.608     albertel 11640: =back
                   11641: 
1.243     albertel 11642: =head2 HTTP Helper Routines
                   11643: 
                   11644: =over 4
                   11645: 
1.191     harris41 11646: =item *
                   11647: 
                   11648: escape() : unpack non-word characters into CGI-compatible hex codes
                   11649: 
                   11650: =item *
                   11651: 
                   11652: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11653: 
1.243     albertel 11654: =back
                   11655: 
                   11656: =head1 PRIVATE SUBROUTINES
                   11657: 
                   11658: =head2 Underlying communication routines (Shouldn't call)
                   11659: 
                   11660: =over 4
                   11661: 
                   11662: =item *
                   11663: 
                   11664: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11665: 
                   11666: =item *
                   11667: 
                   11668: reply() : uses subreply to send a message to remote machine, logs all failures
                   11669: 
                   11670: =item *
                   11671: 
                   11672: critical() : passes a critical message to another server; if cannot
                   11673: get through then place message in connection buffer directory and
                   11674: returns con_delayed, if incapable of saving message, returns
                   11675: con_failed
                   11676: 
                   11677: =item *
                   11678: 
                   11679: reconlonc() : tries to reconnect lonc client processes.
                   11680: 
                   11681: =back
                   11682: 
                   11683: =head2 Resource Access Logging
                   11684: 
                   11685: =over 4
                   11686: 
                   11687: =item *
                   11688: 
                   11689: flushcourselogs() : flush (save) buffer logs and access logs
                   11690: 
                   11691: =item *
                   11692: 
                   11693: courselog($what) : save message for course in hash
                   11694: 
                   11695: =item *
                   11696: 
                   11697: courseacclog($what) : save message for course using &courselog().  Perform
                   11698: special processing for specific resource types (problems, exams, quizzes, etc).
                   11699: 
1.191     harris41 11700: =item *
                   11701: 
                   11702: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11703: as a PerlChildExitHandler
1.243     albertel 11704: 
                   11705: =back
                   11706: 
                   11707: =head2 Other
                   11708: 
                   11709: =over 4
                   11710: 
                   11711: =item *
                   11712: 
                   11713: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11714: 
                   11715: =back
                   11716: 
                   11717: =cut
1.877     foxr     11718: 

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