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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.993   ! raeburn     4: # $Id: lonnet.pm,v 1.992 2009/03/21 21:43:46 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.968     raeburn    79:             $_64bit %env %protocol);
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.807     albertel   95: use LONCAPA qw(:DEFAULT :match);
1.740     www        96: use LONCAPA::Configuration;
1.676     albertel   97: 
1.195     www        98: my $readit;
1.550     foxr       99: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  100: 
1.977     amueller  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    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 {
        !           200:     my ($dom,$lonhost) = @_;
        !           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)) {
        !           215:         my $cachetime = 24*3600;
        !           216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
        !           217:         if (defined($cached)) {
        !           218:             return $loncaparev;
        !           219:         } else {
        !           220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
        !           221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
        !           222:         }
        !           223:     }
        !           224: }
        !           225: 
1.1       albertel  226: # -------------------------------------------------- Non-critical communication
                    227: sub subreply {
                    228:     my ($cmd,$server)=@_;
1.838     albertel  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      230:     #
                    231:     #  With loncnew process trimming, there's a timing hole between lonc server
                    232:     #  process exit and the master server picking up the listen on the AF_UNIX
                    233:     #  socket.  In that time interval, a lock file will exist:
                    234: 
                    235:     my $lockfile=$peerfile.".lock";
                    236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    237: 	sleep(1);
                    238:     }
                    239:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      240:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      241:     #
1.550     foxr      242:     #   We'll give the connection a few tries before abandoning it.  If
                    243:     #   connection is not possible, we'll con_lost back to the client.
                    244:     #   
                    245:     my $client;
                    246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    248: 				      Type    => SOCK_STREAM,
                    249: 				      Timeout => 10);
1.869     albertel  250: 	if ($client) {
1.550     foxr      251: 	    last;		# Connected!
1.850     albertel  252: 	} else {
1.853     albertel  253: 	    &create_connection(&hostname($server),$server);
1.550     foxr      254: 	}
1.850     albertel  255:         sleep(1);		# Try again later if failed connection.
1.550     foxr      256:     }
                    257:     my $answer;
                    258:     if ($client) {
1.704     albertel  259: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      260: 	$answer=<$client>;
                    261: 	if (!$answer) { $answer="con_lost"; }
                    262: 	chomp($answer);
                    263:     } else {
                    264: 	$answer = 'con_lost';	# Failed connection.
                    265:     }
1.1       albertel  266:     return $answer;
                    267: }
                    268: 
                    269: sub reply {
                    270:     my ($cmd,$server)=@_;
1.838     albertel  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  272:     my $answer=subreply($cmd,$server);
1.65      www       273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  274:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       275:                 " $cmd to $server returned $answer</font>");
                    276:     }
1.1       albertel  277:     return $answer;
                    278: }
                    279: 
                    280: # ----------------------------------------------------------- Send USR1 to lonc
                    281: 
                    282: sub reconlonc {
1.891     albertel  283:     my ($lonid) = @_;
                    284:     my $hostname = &hostname($lonid);
                    285:     if ($lonid) {
                    286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    287: 	if ($hostname && -e $peerfile) {
                    288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    290: 					     Type    => SOCK_STREAM,
                    291: 					     Timeout => 10);
                    292: 	    if ($client) {
                    293: 		print $client ("reset_retries\n");
                    294: 		my $answer=<$client>;
                    295: 		#reset just this one.
                    296: 	    }
                    297: 	}
                    298: 	return;
                    299:     }
                    300: 
1.836     www       301:     &logthis("Trying to reconnect lonc");
1.1       albertel  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  303:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  304: 	my $loncpid=<$fh>;
                    305:         chomp($loncpid);
                    306:         if (kill 0 => $loncpid) {
                    307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    308:             kill USR1 => $loncpid;
                    309:             sleep 1;
1.836     www       310:          } else {
1.12      www       311: 	    &logthis(
1.672     albertel  312:                "<font color=\"blue\">WARNING:".
1.12      www       313:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  314:         }
                    315:     } else {
1.836     www       316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  317:     }
                    318: }
                    319: 
                    320: # ------------------------------------------------------ Critical communication
1.12      www       321: 
1.1       albertel  322: sub critical {
                    323:     my ($cmd,$server)=@_;
1.838     albertel  324:     unless (&hostname($server)) {
1.672     albertel  325:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       326:                " Critical message to unknown server ($server)</font>");
                    327:         return 'no_such_host';
                    328:     }
1.1       albertel  329:     my $answer=reply($cmd,$server);
                    330:     if ($answer eq 'con_lost') {
                    331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  332: 	my $answer=reply($cmd,$server);
1.1       albertel  333:         if ($answer eq 'con_lost') {
                    334:             my $now=time;
                    335:             my $middlename=$cmd;
1.5       www       336:             $middlename=substr($middlename,0,16);
1.1       albertel  337:             $middlename=~s/\W//g;
                    338:             my $dfilename=
1.305     www       339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    340:             $dumpcount++;
1.1       albertel  341:             {
1.448     albertel  342: 		my $dfh;
                    343: 		if (open($dfh,">$dfilename")) {
                    344: 		    print $dfh "$cmd\n"; 
                    345: 		    close($dfh);
                    346: 		}
1.1       albertel  347:             }
                    348:             sleep 2;
                    349:             my $wcmd='';
                    350:             {
1.448     albertel  351: 		my $dfh;
                    352: 		if (open($dfh,"<$dfilename")) {
                    353: 		    $wcmd=<$dfh>; 
                    354: 		    close($dfh);
                    355: 		}
1.1       albertel  356:             }
                    357:             chomp($wcmd);
1.7       www       358:             if ($wcmd eq $cmd) {
1.672     albertel  359: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       360:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  361:                 &logperm("D:$server:$cmd");
                    362: 	        return 'con_delayed';
                    363:             } else {
1.672     albertel  364:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       365:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  366:                 &logperm("F:$server:$cmd");
                    367:                 return 'con_failed';
                    368:             }
                    369:         }
                    370:     }
                    371:     return $answer;
1.405     albertel  372: }
                    373: 
1.755     albertel  374: # ------------------------------------------- check if return value is an error
                    375: 
                    376: sub error {
                    377:     my ($result) = @_;
1.756     albertel  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  379: 	if ($2 == 2) { return undef; }
                    380: 	return $1;
                    381:     }
                    382:     return undef;
                    383: }
                    384: 
1.783     albertel  385: sub convert_and_load_session_env {
                    386:     my ($lonidsdir,$handle)=@_;
                    387:     my @profile;
                    388:     {
1.917     albertel  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    390: 	if (!$opened) {
1.915     albertel  391: 	    return 0;
                    392: 	}
1.783     albertel  393: 	flock($idf,LOCK_SH);
                    394: 	@profile=<$idf>;
                    395: 	close($idf);
                    396:     }
                    397:     my %temp_env;
                    398:     foreach my $line (@profile) {
1.786     albertel  399: 	if ($line !~ m/=/) {
                    400: 	    return 0;
                    401: 	}
1.783     albertel  402: 	chomp($line);
                    403: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    405:     }
                    406:     unlink("$lonidsdir/$handle.id");
                    407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    408: 	    0640)) {
                    409: 	%disk_env = %temp_env;
                    410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    411: 	untie(%disk_env);
                    412:     }
1.786     albertel  413:     return 1;
1.783     albertel  414: }
                    415: 
1.374     www       416: # ------------------------------------------- Transfer profile into environment
1.780     albertel  417: my $env_loaded;
                    418: sub transfer_profile_to_env {
1.788     albertel  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    420:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       421: 
1.720     albertel  422:     if (!defined($lonidsdir)) {
                    423: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    424:     }
                    425:     if (!defined($handle)) {
                    426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    427:     }
                    428: 
1.786     albertel  429:     my $convert;
                    430:     {
1.917     albertel  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    432: 	if (!$opened) {
1.915     albertel  433: 	    return;
                    434: 	}
1.786     albertel  435: 	flock($idf,LOCK_SH);
                    436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    437: 		&GDBM_READER(),0640)) {
                    438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    439: 	    untie(%disk_env);
                    440: 	} else {
                    441: 	    $convert = 1;
                    442: 	}
                    443:     }
                    444:     if ($convert) {
                    445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    446: 	    &logthis("Failed to load session, or convert session.");
                    447: 	}
1.374     www       448:     }
1.783     albertel  449: 
1.786     albertel  450:     my %remove;
1.783     albertel  451:     while ( my $envname = each(%env) ) {
1.433     matthew   452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    453:             if ($time < time-300) {
1.783     albertel  454:                 $remove{$key}++;
1.433     matthew   455:             }
                    456:         }
                    457:     }
1.783     albertel  458: 
1.619     albertel  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  460:     $env_loaded=1;
1.783     albertel  461:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   462:         &delenv($expired_key);
1.374     www       463:     }
1.1       albertel  464: }
                    465: 
1.916     albertel  466: # ---------------------------------------------------- Check for valid session 
                    467: sub check_for_valid_session {
                    468:     my ($r) = @_;
                    469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    470:     my $lonid=$cookies{'lonID'};
                    471:     return undef if (!$lonid);
                    472: 
                    473:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    474:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    475:     return undef if (!-e "$lonidsdir/$handle.id");
                    476: 
1.917     albertel  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    478:     return undef if (!$opened);
1.916     albertel  479: 
                    480:     flock($idf,LOCK_SH);
                    481:     my %disk_env;
                    482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    483: 	    &GDBM_READER(),0640)) {
                    484: 	return undef;	
                    485:     }
                    486: 
                    487:     if (!defined($disk_env{'user.name'})
                    488: 	|| !defined($disk_env{'user.domain'})) {
                    489: 	return undef;
                    490:     }
                    491:     return $handle;
                    492: }
                    493: 
1.830     albertel  494: sub timed_flock {
                    495:     my ($file,$lock_type) = @_;
                    496:     my $failed=0;
                    497:     eval {
                    498: 	local $SIG{__DIE__}='DEFAULT';
                    499: 	local $SIG{ALRM}=sub {
                    500: 	    $failed=1;
                    501: 	    die("failed lock");
                    502: 	};
                    503: 	alarm(13);
                    504: 	flock($file,$lock_type);
                    505: 	alarm(0);
                    506:     };
                    507:     if ($failed) {
                    508: 	return undef;
                    509:     } else {
                    510: 	return 1;
                    511:     }
                    512: }
                    513: 
1.5       www       514: # ---------------------------------------------------------- Append Environment
                    515: 
                    516: sub appenv {
1.949     raeburn   517:     my ($newenv,$roles) = @_;
                    518:     if (ref($newenv) eq 'HASH') {
                    519:         foreach my $key (keys(%{$newenv})) {
                    520:             my $refused = 0;
                    521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    522:                 $refused = 1;
                    523:                 if (ref($roles) eq 'ARRAY') {
                    524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    526:                         $refused = 0;
                    527:                     }
                    528:                 }
                    529:             }
                    530:             if ($refused) {
                    531:                 &logthis("<font color=\"blue\">WARNING: ".
                    532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    533:                          .'</font>');
                    534: 	        delete($newenv->{$key});
                    535:             } else {
                    536:                 $env{$key}=$newenv->{$key};
                    537:             }
                    538:         }
                    539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    540:         if ($opened
                    541: 	    && &timed_flock($env_file,LOCK_EX)
                    542: 	    &&
                    543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    545: 	    while (my ($key,$value) = each(%{$newenv})) {
                    546: 	        $disk_env{$key} = $value;
                    547: 	    }
                    548: 	    untie(%disk_env);
1.35      www       549:         }
1.191     harris41  550:     }
1.56      www       551:     return 'ok';
                    552: }
                    553: # ----------------------------------------------------- Delete from Environment
                    554: 
                    555: sub delenv {
1.987     raeburn   556:     my ($delthis,$regexp) = @_;
1.56      www       557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  558:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       559:                 "Attempt to delete from environment ".$delthis);
                    560:         return 'error';
                    561:     }
1.917     albertel  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    563:     if ($opened
1.915     albertel  564: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  565: 	&&
                    566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  568: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   569: 	    if ($regexp) {
                    570:                 if ($key=~/^$delthis/) {
                    571:                     delete($env{$key});
                    572:                     delete($disk_env{$key});
                    573:                 } 
                    574:             } else {
                    575:                 if ($key=~/^\Q$delthis\E/) {
                    576: 		    delete($env{$key});
                    577: 		    delete($disk_env{$key});
                    578: 	        }
                    579:             }
1.448     albertel  580: 	}
1.783     albertel  581: 	untie(%disk_env);
1.5       www       582:     }
                    583:     return 'ok';
1.369     albertel  584: }
                    585: 
1.790     albertel  586: sub get_env_multiple {
                    587:     my ($name) = @_;
                    588:     my @values;
                    589:     if (defined($env{$name})) {
                    590:         # exists is it an array
                    591:         if (ref($env{$name})) {
                    592:             @values=@{ $env{$name} };
                    593:         } else {
                    594:             $values[0]=$env{$name};
                    595:         }
                    596:     }
                    597:     return(@values);
                    598: }
                    599: 
1.958     www       600: # ------------------------------------------------------------------- Locking
                    601: 
                    602: sub set_lock {
                    603:     my ($text)=@_;
                    604:     $locknum++;
                    605:     my $id=$$.'-'.$locknum;
                    606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    607:              'session.lock.'.$id => $text});
                    608:     return $id;
                    609: }
                    610: 
                    611: sub get_locks {
                    612:     my $num=0;
                    613:     my %texts=();
                    614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    615:        if ($lock=~/\w/) {
                    616:           $num++;
                    617:           $texts{$lock}=$env{'session.lock.'.$lock};
                    618:        }
                    619:    }
                    620:    return ($num,%texts);
                    621: }
                    622: 
                    623: sub remove_lock {
                    624:     my ($id)=@_;
                    625:     my $newlocks='';
                    626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    627:        if (($lock=~/\w/) && ($lock ne $id)) {
                    628:           $newlocks.=','.$lock;
                    629:        }
                    630:     }
                    631:     &appenv({'session.locks' => $newlocks});
                    632:     &delenv('session.lock.'.$id);
                    633: }
                    634: 
                    635: sub remove_all_locks {
                    636:     my $activelocks=$env{'session.locks'};
                    637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    638:        if ($lock=~/\w/) {
                    639:           &remove_lock($lock);
                    640:        }
                    641:     }
                    642: }
                    643: 
                    644: 
1.369     albertel  645: # ------------------------------------------ Find out current server userload
                    646: sub userload {
                    647:     my $numusers=0;
                    648:     {
                    649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    650: 	my $filename;
                    651: 	my $curtime=time;
                    652: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  653: 	    next if ($filename eq '.' || $filename eq '..');
                    654: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  657: 	}
                    658: 	closedir(LONIDS);
                    659:     }
                    660:     my $userloadpercent=0;
                    661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    662:     if ($maxuserload) {
1.371     albertel  663: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  664:     }
1.372     albertel  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  666:     return $userloadpercent;
1.283     www       667: }
                    668: 
                    669: # ------------------------------------------ Fight off request when overloaded
                    670: 
                    671: sub overloaderror {
                    672:     my ($r,$checkserver)=@_;
                    673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    674:     my $loadavg;
                    675:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  676:        open(my $loadfile,'/proc/loadavg');
1.283     www       677:        $loadavg=<$loadfile>;
                    678:        $loadavg =~ s/\s.*//g;
1.285     matthew   679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  680:        close($loadfile);
1.283     www       681:     } else {
                    682:        $loadavg=&reply('load',$checkserver);
                    683:     }
1.285     matthew   684:     my $overload=$loadavg-100;
1.283     www       685:     if ($overload>0) {
1.285     matthew   686: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       688:         return 413;
1.283     www       689:     }    
                    690:     return '';
1.5       www       691: }
1.1       albertel  692: 
                    693: # ------------------------------ Find server with least workload from spare.tab
1.11      www       694: 
1.1       albertel  695: sub spareserver {
1.670     albertel  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  697:     my $spare_server;
1.370     albertel  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    700:                                                      :  $userloadpercent;
                    701:     
                    702:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    703: 	($spare_server, $lowest_load) =
                    704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    705:     }
                    706: 
                    707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    708: 
                    709:     if (!$found_server) {
                    710: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    711: 	    ($spare_server, $lowest_load) =
                    712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    713: 	}
                    714:     }
                    715: 
                    716:     if (!$want_server_name) {
1.968     raeburn   717:         my $protocol = 'http';
                    718:         if ($protocol{$spare_server} eq 'https') {
                    719:             $protocol = $protocol{$spare_server};
                    720:         }
                    721: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  722:     }
                    723:     return $spare_server;
                    724: }
                    725: 
                    726: sub compare_server_load {
                    727:     my ($try_server, $spare_server, $lowest_load) = @_;
                    728: 
                    729:     my $loadans     = &reply('load',    $try_server);
                    730:     my $userloadans = &reply('userload',$try_server);
                    731: 
                    732:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    733: 	next; #didn't get a number from the server
                    734:     }
                    735: 
                    736:     my $load;
                    737:     if ($loadans =~ /\d/) {
                    738: 	if ($userloadans =~ /\d/) {
                    739: 	    #both are numbers, pick the bigger one
                    740: 	    $load = ($loadans > $userloadans) ? $loadans 
                    741: 		                              : $userloadans;
1.411     albertel  742: 	} else {
1.784     albertel  743: 	    $load = $loadans;
1.411     albertel  744: 	}
1.784     albertel  745:     } else {
                    746: 	$load = $userloadans;
                    747:     }
                    748: 
                    749:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    750: 	$spare_server = $try_server;
                    751: 	$lowest_load  = $load;
1.370     albertel  752:     }
1.784     albertel  753:     return ($spare_server,$lowest_load);
1.202     matthew   754: }
1.914     albertel  755: 
                    756: # --------------------------- ask offload servers if user already has a session
                    757: sub find_existing_session {
                    758:     my ($udom,$uname) = @_;
                    759:     foreach my $try_server (@{ $spareid{'primary'} },
                    760: 			    @{ $spareid{'default'} }) {
                    761: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    762:     }
                    763:     return;
                    764: }
                    765: 
                    766: # -------------------------------- ask if server already has a session for user
                    767: sub has_user_session {
                    768:     my ($lonid,$udom,$uname) = @_;
                    769:     my $result = &reply(join(':','userhassession',
                    770: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    771:     return 1 if ($result eq 'ok');
                    772: 
                    773:     return 0;
                    774: }
                    775: 
1.202     matthew   776: # --------------------------------------------- Try to change a user's password
                    777: 
                    778: sub changepass {
1.799     raeburn   779:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   780:     $currentpass = &escape($currentpass);
                    781:     $newpass     = &escape($newpass);
1.799     raeburn   782:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   783: 		       $server);
                    784:     if (! $answer) {
                    785: 	&logthis("No reply on password change request to $server ".
                    786: 		 "by $uname in domain $udom.");
                    787:     } elsif ($answer =~ "^ok") {
                    788:         &logthis("$uname in $udom successfully changed their password ".
                    789: 		 "on $server.");
                    790:     } elsif ($answer =~ "^pwchange_failure") {
                    791: 	&logthis("$uname in $udom was unable to change their password ".
                    792: 		 "on $server.  The action was blocked by either lcpasswd ".
                    793: 		 "or pwchange");
                    794:     } elsif ($answer =~ "^non_authorized") {
                    795:         &logthis("$uname in $udom did not get their password correct when ".
                    796: 		 "attempting to change it on $server.");
                    797:     } elsif ($answer =~ "^auth_mode_error") {
                    798:         &logthis("$uname in $udom attempted to change their password despite ".
                    799: 		 "not being locally or internally authenticated on $server.");
                    800:     } elsif ($answer =~ "^unknown_user") {
                    801:         &logthis("$uname in $udom attempted to change their password ".
                    802: 		 "on $server but were unable to because $server is not ".
                    803: 		 "their home server.");
                    804:     } elsif ($answer =~ "^refused") {
                    805: 	&logthis("$server refused to change $uname in $udom password because ".
                    806: 		 "it was sent an unencrypted request to change the password.");
                    807:     }
                    808:     return $answer;
1.1       albertel  809: }
                    810: 
1.169     harris41  811: # ----------------------- Try to determine user's current authentication scheme
                    812: 
                    813: sub queryauthenticate {
                    814:     my ($uname,$udom)=@_;
1.456     albertel  815:     my $uhome=&homeserver($uname,$udom);
                    816:     if (!$uhome) {
                    817: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    818: 	return 'no_host';
                    819:     }
                    820:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    821:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    822: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  823:     }
1.456     albertel  824:     return $answer;
1.169     harris41  825: }
                    826: 
1.1       albertel  827: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       828: 
1.1       albertel  829: sub authenticate {
1.952     raeburn   830:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  831:     $upass=&escape($upass);
                    832:     $uname= &LONCAPA::clean_username($uname);
1.836     www       833:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   834:     my $newhome;
1.836     www       835:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    836: # Maybe the machine was offline and only re-appeared again recently?
                    837:         &reconlonc();
                    838: # One more
1.952     raeburn   839: 	$uhome=&homeserver($uname,$udom,1);
                    840:         if (($uhome eq 'no_host') && $checkdefauth) {
                    841:             if (defined(&domain($udom,'primary'))) {
                    842:                 $newhome=&domain($udom,'primary');
                    843:             }
                    844:             if ($newhome ne '') {
                    845:                 $uhome = $newhome;
                    846:             }
                    847:         }
1.836     www       848: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    849: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   850: 	    return 'no_host';
                    851:         }
1.1       albertel  852:     }
1.952     raeburn   853:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  854:     if ($answer eq 'authorized') {
1.952     raeburn   855:         if ($newhome) {
                    856:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    857:             return 'no_account_on_host'; 
                    858:         } else {
                    859:             &logthis("User $uname at $udom authorized by $uhome");
                    860:             return $uhome;
                    861:         }
1.471     albertel  862:     }
                    863:     if ($answer eq 'non_authorized') {
                    864: 	&logthis("User $uname at $udom rejected by $uhome");
                    865: 	return 'no_host'; 
1.9       www       866:     }
1.471     albertel  867:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  868:     return 'no_host';
                    869: }
                    870: 
                    871: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       872: 
1.599     albertel  873: my %homecache;
1.1       albertel  874: sub homeserver {
1.230     stredwic  875:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  876:     my $index="$uname:$udom";
1.426     albertel  877: 
1.599     albertel  878:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  879: 
                    880:     my %servers = &get_servers($udom,'library');
                    881:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  882:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  883: 		 exists($badServerCache{$tryserver}));
1.841     albertel  884: 
                    885: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    886: 	if ($answer eq 'found') {
                    887: 	    delete($badServerCache{$tryserver}); 
                    888: 	    return $homecache{$index}=$tryserver;
                    889: 	} elsif ($answer eq 'no_host') {
                    890: 	    $badServerCache{$tryserver}=1;
                    891: 	}
1.1       albertel  892:     }    
                    893:     return 'no_host';
1.70      www       894: }
                    895: 
                    896: # ------------------------------------- Find the usernames behind a list of IDs
                    897: 
                    898: sub idget {
                    899:     my ($udom,@ids)=@_;
                    900:     my %returnhash=();
                    901:     
1.841     albertel  902:     my %servers = &get_servers($udom,'library');
                    903:     foreach my $tryserver (keys(%servers)) {
                    904: 	my $idlist=join('&',@ids);
                    905: 	$idlist=~tr/A-Z/a-z/; 
                    906: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    907: 	my @answer=();
                    908: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    909: 	    @answer=split(/\&/,$reply);
                    910: 	}                    ;
                    911: 	my $i;
                    912: 	for ($i=0;$i<=$#ids;$i++) {
                    913: 	    if ($answer[$i]) {
                    914: 		$returnhash{$ids[$i]}=$answer[$i];
                    915: 	    } 
                    916: 	}
                    917:     } 
1.70      www       918:     return %returnhash;
                    919: }
                    920: 
                    921: # ------------------------------------- Find the IDs behind a list of usernames
                    922: 
                    923: sub idrget {
                    924:     my ($udom,@unames)=@_;
                    925:     my %returnhash=();
1.800     albertel  926:     foreach my $uname (@unames) {
                    927:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  928:     }
1.70      www       929:     return %returnhash;
                    930: }
                    931: 
                    932: # ------------------------------- Store away a list of names and associated IDs
                    933: 
                    934: sub idput {
                    935:     my ($udom,%ids)=@_;
                    936:     my %servers=();
1.800     albertel  937:     foreach my $uname (keys(%ids)) {
                    938: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    939:         my $uhom=&homeserver($uname,$udom);
1.70      www       940:         if ($uhom ne 'no_host') {
1.800     albertel  941:             my $id=&escape($ids{$uname});
1.70      www       942:             $id=~tr/A-Z/a-z/;
1.800     albertel  943:             my $esc_unam=&escape($uname);
1.70      www       944: 	    if ($servers{$uhom}) {
1.800     albertel  945: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       946:             } else {
1.800     albertel  947:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       948:             }
                    949:         }
1.191     harris41  950:     }
1.800     albertel  951:     foreach my $server (keys(%servers)) {
                    952:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  953:     }
1.344     www       954: }
                    955: 
1.806     raeburn   956: # ------------------------------------------- get items from domain db files   
                    957: 
                    958: sub get_dom {
1.860     raeburn   959:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   960:     my $items='';
                    961:     foreach my $item (@$storearr) {
                    962:         $items.=&escape($item).'&';
                    963:     }
                    964:     $items=~s/\&$//;
1.860     raeburn   965:     if (!$udom) {
                    966:         $udom=$env{'user.domain'};
                    967:         if (defined(&domain($udom,'primary'))) {
                    968:             $uhome=&domain($udom,'primary');
                    969:         } else {
1.874     albertel  970:             undef($uhome);
1.860     raeburn   971:         }
                    972:     } else {
                    973:         if (!$uhome) {
                    974:             if (defined(&domain($udom,'primary'))) {
                    975:                 $uhome=&domain($udom,'primary');
                    976:             }
                    977:         }
                    978:     }
                    979:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   980:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   981:         my %returnhash;
1.875     albertel  982:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   983:             return %returnhash;
                    984:         }
1.806     raeburn   985:         my @pairs=split(/\&/,$rep);
                    986:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    987:             return @pairs;
                    988:         }
                    989:         my $i=0;
                    990:         foreach my $item (@$storearr) {
                    991:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    992:             $i++;
                    993:         }
                    994:         return %returnhash;
                    995:     } else {
1.880     banghart  996:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   997:     }
                    998: }
                    999: 
                   1000: # -------------------------------------------- put items in domain db files 
                   1001: 
                   1002: sub put_dom {
1.860     raeburn  1003:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1004:     if (!$udom) {
                   1005:         $udom=$env{'user.domain'};
                   1006:         if (defined(&domain($udom,'primary'))) {
                   1007:             $uhome=&domain($udom,'primary');
                   1008:         } else {
1.874     albertel 1009:             undef($uhome);
1.860     raeburn  1010:         }
                   1011:     } else {
                   1012:         if (!$uhome) {
                   1013:             if (defined(&domain($udom,'primary'))) {
                   1014:                 $uhome=&domain($udom,'primary');
                   1015:             }
                   1016:         }
                   1017:     } 
                   1018:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1019:         my $items='';
                   1020:         foreach my $item (keys(%$storehash)) {
                   1021:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1022:         }
                   1023:         $items=~s/\&$//;
                   1024:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1025:     } else {
1.860     raeburn  1026:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1027:     }
                   1028: }
                   1029: 
1.837     raeburn  1030: sub retrieve_inst_usertypes {
                   1031:     my ($udom) = @_;
                   1032:     my (%returnhash,@order);
1.989     raeburn  1033:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1034:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1035:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1036:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1037:         @order = @{$domdefs{'inststatusorder'}};
                   1038:     } else {
                   1039:         if (defined(&domain($udom,'primary'))) {
                   1040:             my $uhome=&domain($udom,'primary');
                   1041:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1042:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1043:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1044:                 return (\%returnhash,\@order);
                   1045:             }
                   1046:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1047:             my @pairs=split(/\&/,$hashitems);
                   1048:             foreach my $item (@pairs) {
                   1049:                 my ($key,$value)=split(/=/,$item,2);
                   1050:                 $key = &unescape($key);
                   1051:                 next if ($key =~ /^error: 2 /);
                   1052:                 $returnhash{$key}=&thaw_unescape($value);
                   1053:             }
                   1054:             my @esc_order = split(/\&/,$orderitems);
                   1055:             foreach my $item (@esc_order) {
                   1056:                 push(@order,&unescape($item));
                   1057:             }
                   1058:         } else {
                   1059:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1060:         }
                   1061:     }
                   1062:     return (\%returnhash,\@order);
                   1063: }
                   1064: 
1.868     raeburn  1065: sub is_domainimage {
                   1066:     my ($url) = @_;
                   1067:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1068:         if (&domain($1) ne '') {
                   1069:             return '1';
                   1070:         }
                   1071:     }
                   1072:     return;
                   1073: }
                   1074: 
1.899     raeburn  1075: sub inst_directory_query {
                   1076:     my ($srch) = @_;
                   1077:     my $udom = $srch->{'srchdomain'};
                   1078:     my %results;
                   1079:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1080:     my $outcome;
1.899     raeburn  1081:     if ($homeserver ne '') {
1.904     albertel 1082: 	my $queryid=&reply("querysend:instdirsearch:".
                   1083: 			   &escape($srch->{'srchby'}).':'.
                   1084: 			   &escape($srch->{'srchterm'}).':'.
                   1085: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1086: 	my $host=&hostname($homeserver);
                   1087: 	if ($queryid !~/^\Q$host\E\_/) {
                   1088: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1089: 	    return;
                   1090: 	}
                   1091: 	my $response = &get_query_reply($queryid);
                   1092: 	my $maxtries = 5;
                   1093: 	my $tries = 1;
                   1094: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1095: 	    $response = &get_query_reply($queryid);
                   1096: 	    $tries ++;
                   1097: 	}
                   1098: 
                   1099:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1100:             if ($response eq 'unavailable') {
                   1101:                 $outcome = $response;
                   1102:             } else {
                   1103:                 $outcome = 'ok';
                   1104:                 my @matches = split(/\n/,$response);
                   1105:                 foreach my $match (@matches) {
                   1106:                     my ($key,$value) = split(/=/,$match);
                   1107:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1108:                 }
1.899     raeburn  1109:             }
                   1110:         }
                   1111:     }
1.909     raeburn  1112:     return ($outcome,%results);
1.899     raeburn  1113: }
                   1114: 
                   1115: sub usersearch {
                   1116:     my ($srch) = @_;
                   1117:     my $dom = $srch->{'srchdomain'};
                   1118:     my %results;
                   1119:     my %libserv = &all_library();
                   1120:     my $query = 'usersearch';
                   1121:     foreach my $tryserver (keys(%libserv)) {
                   1122:         if (&host_domain($tryserver) eq $dom) {
                   1123:             my $host=&hostname($tryserver);
                   1124:             my $queryid=
1.911     raeburn  1125:                 &reply("querysend:".&escape($query).':'.
                   1126:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1127:                        &escape($srch->{'srchtype'}).':'.
                   1128:                        &escape($srch->{'srchterm'}),$tryserver);
                   1129:             if ($queryid !~/^\Q$host\E\_/) {
                   1130:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1131:                 next;
1.899     raeburn  1132:             }
                   1133:             my $reply = &get_query_reply($queryid);
                   1134:             my $maxtries = 1;
                   1135:             my $tries = 1;
                   1136:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1137:                 $reply = &get_query_reply($queryid);
                   1138:                 $tries ++;
                   1139:             }
                   1140:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1141:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1142:             } else {
1.911     raeburn  1143:                 my @matches;
                   1144:                 if ($reply =~ /\n/) {
                   1145:                     @matches = split(/\n/,$reply);
                   1146:                 } else {
                   1147:                     @matches = split(/\&/,$reply);
                   1148:                 }
1.899     raeburn  1149:                 foreach my $match (@matches) {
                   1150:                     my ($uname,$udom,%userhash);
1.911     raeburn  1151:                     foreach my $entry (split(/:/,$match)) {
                   1152:                         my ($key,$value) =
                   1153:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1154:                         $userhash{$key} = $value;
                   1155:                         if ($key eq 'username') {
                   1156:                             $uname = $value;
                   1157:                         } elsif ($key eq 'domain') {
                   1158:                             $udom = $value;
1.911     raeburn  1159:                         }
1.899     raeburn  1160:                     }
                   1161:                     $results{$uname.':'.$udom} = \%userhash;
                   1162:                 }
                   1163:             }
                   1164:         }
                   1165:     }
                   1166:     return %results;
                   1167: }
                   1168: 
1.912     raeburn  1169: sub get_instuser {
                   1170:     my ($udom,$uname,$id) = @_;
                   1171:     my $homeserver = &domain($udom,'primary');
                   1172:     my ($outcome,%results);
                   1173:     if ($homeserver ne '') {
                   1174:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1175:                            &escape($id).':'.&escape($udom),$homeserver);
                   1176:         my $host=&hostname($homeserver);
                   1177:         if ($queryid !~/^\Q$host\E\_/) {
                   1178:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1179:             return;
                   1180:         }
                   1181:         my $response = &get_query_reply($queryid);
                   1182:         my $maxtries = 5;
                   1183:         my $tries = 1;
                   1184:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1185:             $response = &get_query_reply($queryid);
                   1186:             $tries ++;
                   1187:         }
                   1188:         if (!&error($response) && $response ne 'refused') {
                   1189:             if ($response eq 'unavailable') {
                   1190:                 $outcome = $response;
                   1191:             } else {
                   1192:                 $outcome = 'ok';
                   1193:                 my @matches = split(/\n/,$response);
                   1194:                 foreach my $match (@matches) {
                   1195:                     my ($key,$value) = split(/=/,$match);
                   1196:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1197:                 }
                   1198:             }
                   1199:         }
                   1200:     }
                   1201:     my %userinfo;
                   1202:     if (ref($results{$uname}) eq 'HASH') {
                   1203:         %userinfo = %{$results{$uname}};
                   1204:     } 
                   1205:     return ($outcome,%userinfo);
                   1206: }
                   1207: 
                   1208: sub inst_rulecheck {
1.923     raeburn  1209:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1210:     my %returnhash;
                   1211:     if ($udom ne '') {
                   1212:         if (ref($rules) eq 'ARRAY') {
                   1213:             @{$rules} = map {&escape($_);} (@{$rules});
                   1214:             my $rulestr = join(':',@{$rules});
                   1215:             my $homeserver=&domain($udom,'primary');
                   1216:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1217:                 my $response;
                   1218:                 if ($item eq 'username') {                
                   1219:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1220:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1221:                                               $homeserver));
1.923     raeburn  1222:                 } elsif ($item eq 'id') {
                   1223:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1224:                                               ':'.&escape($id).':'.$rulestr,
                   1225:                                               $homeserver));
1.945     raeburn  1226:                 } elsif ($item eq 'selfcreate') {
                   1227:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1228:                                                &escape($udom).':'.&escape($uname).
                   1229:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1230:                 }
1.912     raeburn  1231:                 if ($response ne 'refused') {
                   1232:                     my @pairs=split(/\&/,$response);
                   1233:                     foreach my $item (@pairs) {
                   1234:                         my ($key,$value)=split(/=/,$item,2);
                   1235:                         $key = &unescape($key);
                   1236:                         next if ($key =~ /^error: 2 /);
                   1237:                         $returnhash{$key}=&thaw_unescape($value);
                   1238:                     }
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return %returnhash;
                   1244: }
                   1245: 
                   1246: sub inst_userrules {
1.923     raeburn  1247:     my ($udom,$check) = @_;
1.912     raeburn  1248:     my (%ruleshash,@ruleorder);
                   1249:     if ($udom ne '') {
                   1250:         my $homeserver=&domain($udom,'primary');
                   1251:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1252:             my $response;
                   1253:             if ($check eq 'id') {
                   1254:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1255:                                  $homeserver);
1.943     raeburn  1256:             } elsif ($check eq 'email') {
                   1257:                 $response=&reply('instemailrules:'.&escape($udom),
                   1258:                                  $homeserver);
1.923     raeburn  1259:             } else {
                   1260:                 $response=&reply('instuserrules:'.&escape($udom),
                   1261:                                  $homeserver);
                   1262:             }
1.912     raeburn  1263:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1264:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1265:                 ($response ne 'no_such_host')) {
                   1266:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1267:                 my @pairs=split(/\&/,$hashitems);
                   1268:                 foreach my $item (@pairs) {
                   1269:                     my ($key,$value)=split(/=/,$item,2);
                   1270:                     $key = &unescape($key);
                   1271:                     next if ($key =~ /^error: 2 /);
                   1272:                     $ruleshash{$key}=&thaw_unescape($value);
                   1273:                 }
                   1274:                 my @esc_order = split(/\&/,$orderitems);
                   1275:                 foreach my $item (@esc_order) {
                   1276:                     push(@ruleorder,&unescape($item));
                   1277:                 }
                   1278:             }
                   1279:         }
                   1280:     }
                   1281:     return (\%ruleshash,\@ruleorder);
                   1282: }
                   1283: 
1.976     raeburn  1284: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1285: 
                   1286: sub get_domain_defaults {
                   1287:     my ($domain) = @_;
                   1288:     my $cachetime = 60*60*24;
                   1289:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1290:     if (defined($cached)) {
                   1291:         if (ref($result) eq 'HASH') {
                   1292:             return %{$result};
                   1293:         }
                   1294:     }
                   1295:     my %domdefaults;
                   1296:     my %domconfig =
1.989     raeburn  1297:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1298:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1299:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1300:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1301:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1302:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1303:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1304:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1305:     } else {
                   1306:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1307:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1308:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1309:     }
1.976     raeburn  1310:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1311:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1312:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1313:         } else {
                   1314:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1315:         } 
                   1316:         my @usertools = ('aboutme','blog','portfolio');
                   1317:         foreach my $item (@usertools) {
                   1318:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1319:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1320:             }
                   1321:         }
                   1322:     }
1.985     raeburn  1323:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
                   1324:         foreach my $item ('official','unofficial') {
                   1325:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1326:         }
                   1327:     }
1.989     raeburn  1328:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1329:         foreach my $item ('inststatustypes','inststatusorder') {
                   1330:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1331:         }
                   1332:     }
1.943     raeburn  1333:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1334:                                   $cachetime);
                   1335:     return %domdefaults;
                   1336: }
                   1337: 
1.344     www      1338: # --------------------------------------------------- Assign a key to a student
                   1339: 
                   1340: sub assign_access_key {
1.364     www      1341: #
                   1342: # a valid key looks like uname:udom#comments
                   1343: # comments are being appended
                   1344: #
1.498     www      1345:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1346:     $kdom=
1.620     albertel 1347:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1348:     $knum=
1.620     albertel 1349:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1350:     $cdom=
1.620     albertel 1351:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1352:     $cnum=
1.620     albertel 1353:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1354:     $udom=$env{'user.name'} unless (defined($udom));
                   1355:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1356:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1357:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1358:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1359:                                                   # assigned to this person
                   1360:                                                   # - this should not happen,
1.345     www      1361:                                                   # unless something went wrong
                   1362:                                                   # the first time around
                   1363: # ready to assign
1.364     www      1364:         $logentry=$1.'; '.$logentry;
1.496     www      1365:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1366:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1367: # key now belongs to user
1.346     www      1368: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1369:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1370:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1371:                 return 'ok';
                   1372:             } else {
                   1373:                 return 
                   1374:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1375: 	    }
                   1376:         } else {
                   1377:             return 'error: Could not assign key, try again later.';
                   1378:         }
1.364     www      1379:     } elsif (!$existing{$ckey}) {
1.345     www      1380: # the key does not exist
                   1381: 	return 'error: The key does not exist';
                   1382:     } else {
                   1383: # the key is somebody else's
                   1384: 	return 'error: The key is already in use';
                   1385:     }
1.344     www      1386: }
                   1387: 
1.364     www      1388: # ------------------------------------------ put an additional comment on a key
                   1389: 
                   1390: sub comment_access_key {
                   1391: #
                   1392: # a valid key looks like uname:udom#comments
                   1393: # comments are being appended
                   1394: #
                   1395:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1396:     $cdom=
1.620     albertel 1397:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1398:     $cnum=
1.620     albertel 1399:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1400:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1401:     if ($existing{$ckey}) {
                   1402:         $existing{$ckey}.='; '.$logentry;
                   1403: # ready to assign
1.367     www      1404:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1405:                                                  $cdom,$cnum) eq 'ok') {
                   1406: 	    return 'ok';
                   1407:         } else {
                   1408: 	    return 'error: Count not store comment.';
                   1409:         }
                   1410:     } else {
                   1411: # the key does not exist
                   1412: 	return 'error: The key does not exist';
                   1413:     }
                   1414: }
                   1415: 
1.344     www      1416: # ------------------------------------------------------ Generate a set of keys
                   1417: 
                   1418: sub generate_access_keys {
1.364     www      1419:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1420:     $cdom=
1.620     albertel 1421:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1422:     $cnum=
1.620     albertel 1423:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1424:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1425:     unless (($cdom) && ($cnum)) { return 0; }
                   1426:     if ($number>10000) { return 0; }
                   1427:     sleep(2); # make sure don't get same seed twice
                   1428:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1429:     my $total=0;
                   1430:     for (my $i=1;$i<=$number;$i++) {
                   1431:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1432:                   sprintf("%lx",int(100000*rand)).'-'.
                   1433:                   sprintf("%lx",int(100000*rand));
                   1434:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1435:        $newkey=~s/0/h/g; # and also 0 and O
                   1436:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1437:        if ($existing{$newkey}) {
                   1438:            $i--;
                   1439:        } else {
1.364     www      1440: 	  if (&put('accesskeys',
                   1441:               { $newkey => '# generated '.localtime().
1.620     albertel 1442:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1443:                            '; '.$logentry },
                   1444: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1445:               $total++;
                   1446: 	  }
                   1447:        }
                   1448:     }
1.620     albertel 1449:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1450:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1451:     return $total;
                   1452: }
                   1453: 
                   1454: # ------------------------------------------------------- Validate an accesskey
                   1455: 
                   1456: sub validate_access_key {
                   1457:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1458:     $cdom=
1.620     albertel 1459:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1460:     $cnum=
1.620     albertel 1461:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1462:     $udom=$env{'user.domain'} unless (defined($udom));
                   1463:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1465:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1466: }
                   1467: 
                   1468: # ------------------------------------- Find the section of student in a course
1.652     albertel 1469: sub devalidate_getsection_cache {
                   1470:     my ($udom,$unam,$courseid)=@_;
                   1471:     my $hashid="$udom:$unam:$courseid";
                   1472:     &devalidate_cache_new('getsection',$hashid);
                   1473: }
1.298     matthew  1474: 
1.815     albertel 1475: sub courseid_to_courseurl {
                   1476:     my ($courseid) = @_;
                   1477:     #already url style courseid
                   1478:     return $courseid if ($courseid =~ m{^/});
                   1479: 
                   1480:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1481: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1482: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1483: 	return "/$cdom/$cnum";
                   1484:     }
                   1485: 
                   1486:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1487:     if (exists($courseinfo{'num'})) {
                   1488: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1489:     }
                   1490: 
                   1491:     return undef;
                   1492: }
                   1493: 
1.298     matthew  1494: sub getsection {
                   1495:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1496:     my $cachetime=1800;
1.551     albertel 1497: 
                   1498:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1499:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1500:     if (defined($cached)) { return $result; }
                   1501: 
1.298     matthew  1502:     my %Pending; 
                   1503:     my %Expired;
                   1504:     #
                   1505:     # Each role can either have not started yet (pending), be active, 
                   1506:     #    or have expired.
                   1507:     #
                   1508:     # If there is an active role, we are done.
                   1509:     #
                   1510:     # If there is more than one role which has not started yet, 
                   1511:     #     choose the one which will start sooner
                   1512:     # If there is one role which has not started yet, return it.
                   1513:     #
                   1514:     # If there is more than one expired role, choose the one which ended last.
                   1515:     # If there is a role which has expired, return it.
                   1516:     #
1.815     albertel 1517:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1518:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1519:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1520:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1521:         my $section=$1;
                   1522:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1523:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1524:         my $now=time;
1.548     albertel 1525:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1526:             $Expired{$end}=$section;
                   1527:             next;
                   1528:         }
1.548     albertel 1529:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1530:             $Pending{$start}=$section;
                   1531:             next;
                   1532:         }
1.599     albertel 1533:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1534:     }
                   1535:     #
                   1536:     # Presumedly there will be few matching roles from the above
                   1537:     # loop and the sorting time will be negligible.
                   1538:     if (scalar(keys(%Pending))) {
                   1539:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1540:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1541:     } 
                   1542:     if (scalar(keys(%Expired))) {
                   1543:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1544:         my $time = pop(@sorted);
1.599     albertel 1545:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1546:     }
1.599     albertel 1547:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1548: }
1.70      www      1549: 
1.599     albertel 1550: sub save_cache {
                   1551:     &purge_remembered();
1.722     albertel 1552:     #&Apache::loncommon::validate_page();
1.620     albertel 1553:     undef(%env);
1.780     albertel 1554:     undef($env_loaded);
1.599     albertel 1555: }
1.452     albertel 1556: 
1.599     albertel 1557: my $to_remember=-1;
                   1558: my %remembered;
                   1559: my %accessed;
                   1560: my $kicks=0;
                   1561: my $hits=0;
1.849     albertel 1562: sub make_key {
                   1563:     my ($name,$id) = @_;
1.872     albertel 1564:     if (length($id) > 65 
                   1565: 	&& length(&escape($id)) > 200) {
                   1566: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1567:     }
1.849     albertel 1568:     return &escape($name.':'.$id);
                   1569: }
                   1570: 
1.599     albertel 1571: sub devalidate_cache_new {
                   1572:     my ($name,$id,$debug) = @_;
                   1573:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1574:     $id=&make_key($name,$id);
1.599     albertel 1575:     $memcache->delete($id);
                   1576:     delete($remembered{$id});
                   1577:     delete($accessed{$id});
                   1578: }
                   1579: 
                   1580: sub is_cached_new {
                   1581:     my ($name,$id,$debug) = @_;
1.849     albertel 1582:     $id=&make_key($name,$id);
1.599     albertel 1583:     if (exists($remembered{$id})) {
                   1584: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1585: 	$accessed{$id}=[&gettimeofday()];
                   1586: 	$hits++;
                   1587: 	return ($remembered{$id},1);
                   1588:     }
                   1589:     my $value = $memcache->get($id);
                   1590:     if (!(defined($value))) {
                   1591: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1592: 	return (undef,undef);
1.416     albertel 1593:     }
1.599     albertel 1594:     if ($value eq '__undef__') {
                   1595: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1596: 	$value=undef;
                   1597:     }
                   1598:     &make_room($id,$value,$debug);
                   1599:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1600:     return ($value,1);
                   1601: }
                   1602: 
                   1603: sub do_cache_new {
                   1604:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1605:     $id=&make_key($name,$id);
1.599     albertel 1606:     my $setvalue=$value;
                   1607:     if (!defined($setvalue)) {
                   1608: 	$setvalue='__undef__';
                   1609:     }
1.623     albertel 1610:     if (!defined($time) ) {
                   1611: 	$time=600;
                   1612:     }
1.599     albertel 1613:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1614:     my $result = $memcache->set($id,$setvalue,$time);
                   1615:     if (! $result) {
1.872     albertel 1616: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1617: 	$memcache->disconnect_all();
1.872     albertel 1618:     }
1.600     albertel 1619:     # need to make a copy of $value
1.919     albertel 1620:     &make_room($id,$value,$debug);
1.599     albertel 1621:     return $value;
                   1622: }
                   1623: 
                   1624: sub make_room {
                   1625:     my ($id,$value,$debug)=@_;
1.919     albertel 1626: 
                   1627:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1628:                                     : $value;
1.599     albertel 1629:     if ($to_remember<0) { return; }
                   1630:     $accessed{$id}=[&gettimeofday()];
                   1631:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1632:     my $to_kick;
                   1633:     my $max_time=0;
                   1634:     foreach my $other (keys(%accessed)) {
                   1635: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1636: 	    $to_kick=$other;
                   1637: 	    $max_time=&tv_interval($accessed{$other});
                   1638: 	}
                   1639:     }
                   1640:     delete($remembered{$to_kick});
                   1641:     delete($accessed{$to_kick});
                   1642:     $kicks++;
                   1643:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1644:     return;
                   1645: }
                   1646: 
1.599     albertel 1647: sub purge_remembered {
1.604     albertel 1648:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1649:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1650:     undef(%remembered);
                   1651:     undef(%accessed);
1.428     albertel 1652: }
1.70      www      1653: # ------------------------------------- Read an entry from a user's environment
                   1654: 
                   1655: sub userenvironment {
                   1656:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1657:     my $items;
                   1658:     foreach my $item (@what) {
                   1659:         $items.=&escape($item).'&';
                   1660:     }
                   1661:     $items=~s/\&$//;
1.70      www      1662:     my %returnhash=();
                   1663:     my @answer=split(/\&/,
1.976     raeburn  1664:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1665:                       &homeserver($unam,$udom)));
                   1666:     my $i;
                   1667:     for ($i=0;$i<=$#what;$i++) {
                   1668: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1669:     }
                   1670:     return %returnhash;
1.1       albertel 1671: }
                   1672: 
1.617     albertel 1673: # ---------------------------------------------------------- Get a studentphoto
                   1674: sub studentphoto {
                   1675:     my ($udom,$unam,$ext) = @_;
                   1676:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1677:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1678:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1679:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1680:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1681:             } else {
                   1682:                 my ($result,$perm_reqd)=
1.707     albertel 1683: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1684:                 if ($result eq 'ok') {
                   1685:                     if (!($perm_reqd eq 'yes')) {
                   1686:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1687:                     }
                   1688:                 }
                   1689:             }
                   1690:         }
                   1691:     } else {
                   1692:         my ($result,$perm_reqd) = 
1.707     albertel 1693: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1694:         if ($result eq 'ok') {
                   1695:             if (!($perm_reqd eq 'yes')) {
                   1696:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1697:             }
                   1698:         }
                   1699:     }
                   1700:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1701: }
                   1702: 
                   1703: sub retrievestudentphoto {
                   1704:     my ($udom,$unam,$ext,$type) = @_;
                   1705:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1706:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1707:     if ($ret eq 'ok') {
                   1708:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1709:         if ($type eq 'thumbnail') {
                   1710:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1711:         }
                   1712:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1713:         return $tokenurl;
                   1714:     } else {
                   1715:         if ($type eq 'thumbnail') {
                   1716:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1717:         } else { 
                   1718:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1719:         }
1.617     albertel 1720:     }
                   1721: }
                   1722: 
1.263     www      1723: # -------------------------------------------------------------------- New chat
                   1724: 
                   1725: sub chatsend {
1.724     raeburn  1726:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1727:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1728:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1729:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1730:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1731: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1732: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1733: }
                   1734: 
                   1735: # ------------------------------------------ Find current version of a resource
                   1736: 
                   1737: sub getversion {
                   1738:     my $fname=&clutter(shift);
                   1739:     unless ($fname=~/^\/res\//) { return -1; }
                   1740:     return &currentversion(&filelocation('',$fname));
                   1741: }
                   1742: 
                   1743: sub currentversion {
                   1744:     my $fname=shift;
1.599     albertel 1745:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1746:     if (defined($cached)) { return $result; }
1.292     www      1747:     my $author=$fname;
                   1748:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1749:     my ($udom,$uname)=split(/\//,$author);
                   1750:     my $home=homeserver($uname,$udom);
                   1751:     if ($home eq 'no_host') { 
                   1752:         return -1; 
                   1753:     }
                   1754:     my $answer=reply("currentversion:$fname",$home);
                   1755:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1756: 	return -1;
                   1757:     }
1.599     albertel 1758:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1759: }
                   1760: 
1.1       albertel 1761: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1762: 
1.1       albertel 1763: sub subscribe {
                   1764:     my $fname=shift;
1.761     raeburn  1765:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1766:     $fname=~s/[\n\r]//g;
1.1       albertel 1767:     my $author=$fname;
                   1768:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1769:     my ($udom,$uname)=split(/\//,$author);
                   1770:     my $home=homeserver($uname,$udom);
1.335     albertel 1771:     if ($home eq 'no_host') {
                   1772:         return 'not_found';
1.1       albertel 1773:     }
                   1774:     my $answer=reply("sub:$fname",$home);
1.64      www      1775:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1776: 	$answer.=' by '.$home;
                   1777:     }
1.1       albertel 1778:     return $answer;
                   1779: }
                   1780:     
1.8       www      1781: # -------------------------------------------------------------- Replicate file
                   1782: 
                   1783: sub repcopy {
                   1784:     my $filename=shift;
1.23      www      1785:     $filename=~s/\/+/\//g;
1.607     raeburn  1786:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1787:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1788:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1789: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1790: 	return &repcopy_userfile($filename);
                   1791:     }
1.532     albertel 1792:     $filename=~s/[\n\r]//g;
1.8       www      1793:     my $transname="$filename.in.transfer";
1.828     www      1794: # FIXME: this should flock
1.607     raeburn  1795:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1796:     my $remoteurl=subscribe($filename);
1.64      www      1797:     if ($remoteurl =~ /^con_lost by/) {
                   1798: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1799:            return 'unavailable';
1.8       www      1800:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1801: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1802: 	   return 'not_found';
1.64      www      1803:     } elsif ($remoteurl =~ /^rejected by/) {
                   1804: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1805:            return 'forbidden';
1.20      www      1806:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1807:            return 'ok';
1.8       www      1808:     } else {
1.290     www      1809:         my $author=$filename;
                   1810:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1811:         my ($udom,$uname)=split(/\//,$author);
                   1812:         my $home=homeserver($uname,$udom);
                   1813:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1814:            my @parts=split(/\//,$filename);
                   1815:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1816:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1817:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1818: 	       return 'bad_request';
1.8       www      1819:            }
                   1820:            my $count;
                   1821:            for ($count=5;$count<$#parts;$count++) {
                   1822:                $path.="/$parts[$count]";
                   1823:                if ((-e $path)!=1) {
                   1824: 		   mkdir($path,0777);
                   1825:                }
                   1826:            }
                   1827:            my $ua=new LWP::UserAgent;
                   1828:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1829:            my $response=$ua->request($request,$transname);
                   1830:            if ($response->is_error()) {
                   1831: 	       unlink($transname);
                   1832:                my $message=$response->status_line;
1.672     albertel 1833:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1834:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1835:                return 'unavailable';
1.8       www      1836:            } else {
1.16      www      1837: 	       if ($remoteurl!~/\.meta$/) {
                   1838:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1839:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1840:                   if ($mresponse->is_error()) {
                   1841: 		      unlink($filename.'.meta');
                   1842:                       &logthis(
1.672     albertel 1843:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1844:                   }
                   1845: 	       }
1.8       www      1846:                rename($transname,$filename);
1.607     raeburn  1847:                return 'ok';
1.8       www      1848:            }
1.290     www      1849:        }
1.8       www      1850:     }
1.330     www      1851: }
                   1852: 
                   1853: # ------------------------------------------------ Get server side include body
                   1854: sub ssi_body {
1.381     albertel 1855:     my ($filelink,%form)=@_;
1.606     matthew  1856:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1857:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1858:     }
1.953     www      1859:     my $output='';
                   1860:     my $response;
1.980     raeburn  1861:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1862:        ($output,$response)=&externalssi($filelink);
1.953     www      1863:     } else {
                   1864:        ($output,$response)=&ssi($filelink,%form);
                   1865:     }
1.778     albertel 1866:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1867:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1868:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1869:     if (wantarray) {
                   1870:         return ($output, $response);
                   1871:     } else {
                   1872:         return $output;
                   1873:     }
1.8       www      1874: }
                   1875: 
1.15      www      1876: # --------------------------------------------------------- Server Side Include
                   1877: 
1.782     albertel 1878: sub absolute_url {
                   1879:     my ($host_name) = @_;
                   1880:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1881:     if ($host_name eq '') {
                   1882: 	$host_name = $ENV{'SERVER_NAME'};
                   1883:     }
                   1884:     return $protocol.$host_name;
                   1885: }
                   1886: 
1.942     foxr     1887: #
                   1888: #   Server side include.
                   1889: # Parameters:
                   1890: #  fn     Possibly encrypted resource name/id.
                   1891: #  form   Hash that describes how the rendering should be done
                   1892: #         and other things.
1.944     foxr     1893: # Returns:
1.950     raeburn  1894: #   Scalar context: The content of the response.
                   1895: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1896: #     
1.15      www      1897: sub ssi {
                   1898: 
1.944     foxr     1899:     my ($fn,%form)=@_;
1.15      www      1900:     my $ua=new LWP::UserAgent;
1.23      www      1901:     my $request;
1.711     albertel 1902: 
                   1903:     $form{'no_update_last_known'}=1;
1.895     albertel 1904:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1905:     if (%form) {
1.782     albertel 1906:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1907:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1908:     } else {
1.782     albertel 1909:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1910:     }
                   1911: 
1.15      www      1912:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1913:     my $response=$ua->request($request);
                   1914: 
1.944     foxr     1915:     if (wantarray) {
                   1916: 	return ($response->content, $response);
                   1917:     } else {
                   1918: 	return $response->content;
1.942     foxr     1919:     }
1.324     www      1920: }
                   1921: 
                   1922: sub externalssi {
                   1923:     my ($url)=@_;
                   1924:     my $ua=new LWP::UserAgent;
                   1925:     my $request=new HTTP::Request('GET',$url);
                   1926:     my $response=$ua->request($request);
1.954     raeburn  1927:     if (wantarray) {
                   1928:         return ($response->content, $response);
                   1929:     } else {
                   1930:         return $response->content;
                   1931:     }
1.15      www      1932: }
1.254     www      1933: 
1.492     albertel 1934: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1935: 
                   1936: sub allowuploaded {
                   1937:     my ($srcurl,$url)=@_;
                   1938:     $url=&clutter(&declutter($url));
                   1939:     my $dir=$url;
                   1940:     $dir=~s/\/[^\/]+$//;
                   1941:     my %httpref=();
                   1942:     my $httpurl=&hreflocation('',$url);
                   1943:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1944:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1945: }
1.477     raeburn  1946: 
1.478     albertel 1947: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1948: # input: action, courseID, current domain, intended
1.637     raeburn  1949: #        path to file, source of file, instruction to parse file for objects,
                   1950: #        ref to hash for embedded objects,
                   1951: #        ref to hash for codebase of java objects.
                   1952: #
1.485     raeburn  1953: # output: url to file (if action was uploaddoc), 
                   1954: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1955: #
1.478     albertel 1956: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1957: # course.
1.477     raeburn  1958: #
1.478     albertel 1959: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1960: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1961: #          course's home server.
1.477     raeburn  1962: #
1.478     albertel 1963: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1964: #          be copied from $source (current location) to 
                   1965: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1966: #         and will then be copied to
                   1967: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1968: #         course's home server.
1.485     raeburn  1969: #
1.481     raeburn  1970: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1971: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1972: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1973: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1974: #         in course's home server.
1.637     raeburn  1975: #
1.477     raeburn  1976: 
                   1977: sub process_coursefile {
1.638     albertel 1978:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1979:     my $fetchresult;
1.638     albertel 1980:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1981:     if ($action eq 'propagate') {
1.638     albertel 1982:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1983: 			     $home);
1.481     raeburn  1984:     } else {
1.477     raeburn  1985:         my $fpath = '';
                   1986:         my $fname = $file;
1.478     albertel 1987:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1988:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1989:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1990:         if ($action eq 'copy') {
                   1991:             if ($source eq '') {
                   1992:                 $fetchresult = 'no source file';
                   1993:                 return $fetchresult;
                   1994:             } else {
                   1995:                 my $destination = $filepath.'/'.$fname;
                   1996:                 rename($source,$destination);
                   1997:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1998:                                  $home);
1.481     raeburn  1999:             }
                   2000:         } elsif ($action eq 'uploaddoc') {
                   2001:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2002:             print $fh $env{'form.'.$source};
1.481     raeburn  2003:             close($fh);
1.637     raeburn  2004:             if ($parser eq 'parse') {
1.961     raeburn  2005:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  2006:                 unless ($parse_result eq 'ok') {
                   2007:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2008:                 }
                   2009:             }
1.477     raeburn  2010:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2011:                                  $home);
1.481     raeburn  2012:             if ($fetchresult eq 'ok') {
                   2013:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2014:             } else {
                   2015:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2016:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2017:                 return '/adm/notfound.html';
                   2018:             }
1.477     raeburn  2019:         }
                   2020:     }
1.485     raeburn  2021:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2022:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2023:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2024:     }
                   2025:     return $fetchresult;
                   2026: }
                   2027: 
1.637     raeburn  2028: sub build_filepath {
                   2029:     my ($fpath) = @_;
                   2030:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2031:     unless ($fpath eq '') {
                   2032:         my @parts=split('/',$fpath);
                   2033:         foreach my $part (@parts) {
                   2034:             $filepath.= '/'.$part;
                   2035:             if ((-e $filepath)!=1) {
                   2036:                 mkdir($filepath,0777);
                   2037:             }
                   2038:         }
                   2039:     }
                   2040:     return $filepath;
                   2041: }
                   2042: 
                   2043: sub store_edited_file {
1.638     albertel 2044:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2045:     my $file = $primary_url;
                   2046:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2047:     my $fpath = '';
                   2048:     my $fname = $file;
                   2049:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2050:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2051:     my $filepath = &build_filepath($fpath);
                   2052:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2053:     print $fh $content;
                   2054:     close($fh);
1.638     albertel 2055:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2056:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2057: 			  $home);
1.637     raeburn  2058:     if ($$fetchresult eq 'ok') {
                   2059:         return '/uploaded/'.$fpath.'/'.$fname;
                   2060:     } else {
1.638     albertel 2061:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2062: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2063:         return '/adm/notfound.html';
                   2064:     }
                   2065: }
                   2066: 
1.531     albertel 2067: sub clean_filename {
1.831     albertel 2068:     my ($fname,$args)=@_;
1.315     www      2069: # Replace Windows backslashes by forward slashes
1.257     www      2070:     $fname=~s/\\/\//g;
1.831     albertel 2071:     if (!$args->{'keep_path'}) {
                   2072:         # Get rid of everything but the actual filename
                   2073: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2074:     }
1.315     www      2075: # Replace spaces by underscores
                   2076:     $fname=~s/\s+/\_/g;
                   2077: # Replace all other weird characters by nothing
1.831     albertel 2078:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2079: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2080: # numbers
                   2081:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2082:     return $fname;
                   2083: }
1.984     neumanie 2084: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2085: sub resizeImage {
                   2086: 	my($img_url) = @_;	
                   2087: 	my $ima = Image::Magick->new;                       
                   2088:         $ima->Read($img_url);
                   2089: 	if($ima->Get('width') > 400)
                   2090: 	{
                   2091: 		my $factor = $ima->Get('width')/400;
                   2092:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2093: 	}
                   2094: 	if($ima->Get('height') > 500)
                   2095:         {
                   2096:         	my $factor = $ima->Get('height')/500;
                   2097:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2098:         } 
                   2099: 		
                   2100: 	$ima->Write($img_url);
                   2101: }
1.531     albertel 2102: 
1.977     amueller 2103: #Wrapper function for userphotoupload
                   2104: sub userphotoupload
                   2105: {
                   2106: 	my($formname,$subdir) = @_;
                   2107: 	$upload_photo_form = 1;
                   2108: 	return &userfileupload($formname,undef,$subdir);
                   2109: }
                   2110: 
1.608     albertel 2111: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2112: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2113: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2114: #        $coursedoc - if true up to the current course
                   2115: #                     if false
                   2116: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2117: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2118: #        $allfiles - reference to hash for embedded objects
                   2119: #        $codebase - reference to hash for codebase of java objects
                   2120: #        $desuname - username for permanent storage of uploaded file
                   2121: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2122: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2123: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2124: # 
1.686     albertel 2125: # output: url of file in userspace, or error: <message> 
                   2126: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2127: 
                   2128: 
1.531     albertel 2129: sub userfileupload {
1.860     raeburn  2130:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2131:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2132:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2133:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2134:     $fname=&clean_filename($fname);
1.315     www      2135: # See if there is anything left
1.257     www      2136:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2137:     chop($env{'form.'.$formname});
1.523     raeburn  2138:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2139:         my $now = time;
                   2140:         my $filepath = 'tmp/helprequests/'.$now;
                   2141:         my @parts=split(/\//,$filepath);
                   2142:         my $fullpath = $perlvar{'lonDaemons'};
                   2143:         for (my $i=0;$i<@parts;$i++) {
                   2144:             $fullpath .= '/'.$parts[$i];
                   2145:             if ((-e $fullpath)!=1) {
                   2146:                 mkdir($fullpath,0777);
                   2147:             }
                   2148:         }
                   2149:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2150:         print $fh $env{'form.'.$formname};
1.523     raeburn  2151:         close($fh);
1.741     raeburn  2152:         return $fullpath.'/'.$fname;
                   2153:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2154:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2155:                        '_'.$env{'user.domain'}.'/pending';
                   2156:         my @parts=split(/\//,$filepath);
                   2157:         my $fullpath = $perlvar{'lonDaemons'};
                   2158:         for (my $i=0;$i<@parts;$i++) {
                   2159:             $fullpath .= '/'.$parts[$i];
                   2160:             if ((-e $fullpath)!=1) {
                   2161:                 mkdir($fullpath,0777);
                   2162:             }
                   2163:         }
                   2164:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2165:         print $fh $env{'form.'.$formname};
                   2166:         close($fh);
                   2167:         return $fullpath.'/'.$fname;
1.523     raeburn  2168:     }
1.719     banghart 2169:     
1.258     www      2170: # Create the directory if not present
1.493     albertel 2171:     $fname="$subdir/$fname";
1.259     www      2172:     if ($coursedoc) {
1.638     albertel 2173: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2174: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2175:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2176:             return &finishuserfileupload($docuname,$docudom,
                   2177: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2178: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2179:         } else {
1.620     albertel 2180:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2181:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2182: 				       $fname,$formname,$parser,
                   2183: 				       $allfiles,$codebase);
1.481     raeburn  2184:         }
1.719     banghart 2185:     } elsif (defined($destuname)) {
                   2186:         my $docuname=$destuname;
                   2187:         my $docudom=$destudom;
1.860     raeburn  2188: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2189: 				     $parser,$allfiles,$codebase,
                   2190:                                      $thumbwidth,$thumbheight);
1.719     banghart 2191:         
1.259     www      2192:     } else {
1.638     albertel 2193:         my $docuname=$env{'user.name'};
                   2194:         my $docudom=$env{'user.domain'};
1.714     raeburn  2195:         if (exists($env{'form.group'})) {
                   2196:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2197:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2198:         }
1.860     raeburn  2199: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2200: 				     $parser,$allfiles,$codebase,
                   2201:                                      $thumbwidth,$thumbheight);
1.259     www      2202:     }
1.271     www      2203: }
                   2204: 
                   2205: sub finishuserfileupload {
1.860     raeburn  2206:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2207:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2208:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2209:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2210:   
1.860     raeburn  2211:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2212:     $file=$fname;
                   2213:     if ($fname=~m|/|) {
                   2214:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2215: 	$path.=$fnamepath.'/';
                   2216:     }
1.259     www      2217:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2218:     my $count;
                   2219:     for ($count=4;$count<=$#parts;$count++) {
                   2220:         $filepath.="/$parts[$count]";
                   2221:         if ((-e $filepath)!=1) {
                   2222: 	    mkdir($filepath,0777);
                   2223:         }
                   2224:     }
1.984     neumanie 2225: 
1.258     www      2226: # Save the file
                   2227:     {
1.701     albertel 2228: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2229: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2230: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2231: 	    return '/adm/notfound.html';
                   2232: 	}
                   2233: 	if (!print FH ($env{'form.'.$formname})) {
                   2234: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2235: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2236: 	    return '/adm/notfound.html';
                   2237: 	}
1.570     albertel 2238: 	close(FH);
1.977     amueller 2239: 	if($upload_photo_form==1)
                   2240: 	{
1.984     neumanie 2241: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2242: 		$upload_photo_form = 0;
                   2243: 	}
1.258     www      2244:     }
1.637     raeburn  2245:     if ($parser eq 'parse') {
1.961     raeburn  2246:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2247: 						   $codebase);
1.637     raeburn  2248:         unless ($parse_result eq 'ok') {
1.638     albertel 2249:             &logthis('Failed to parse '.$filepath.$file.
                   2250: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2251:         }
                   2252:     }
1.860     raeburn  2253:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2254:         my $input = $filepath.'/'.$file;
                   2255:         my $output = $filepath.'/'.'tn-'.$file;
                   2256:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2257:         system("convert -sample $thumbsize $input $output");
                   2258:         if (-e $filepath.'/'.'tn-'.$file) {
                   2259:             $fetchthumb  = 1; 
                   2260:         }
                   2261:     }
1.858     raeburn  2262:  
1.259     www      2263: # Notify homeserver to grep it
                   2264: #
1.984     neumanie 2265:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2266:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2267:     if ($fetchresult eq 'ok') {
1.860     raeburn  2268:         if ($fetchthumb) {
                   2269:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2270:             if ($thumbresult ne 'ok') {
                   2271:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2272:                          $docuhome.': '.$thumbresult);
                   2273:             }
                   2274:         }
1.259     www      2275: #
1.258     www      2276: # Return the URL to it
1.494     albertel 2277:         return '/uploaded/'.$path.$file;
1.263     www      2278:     } else {
1.494     albertel 2279:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2280: 		 ': '.$fetchresult);
1.263     www      2281:         return '/adm/notfound.html';
1.858     raeburn  2282:     }
1.493     albertel 2283: }
                   2284: 
1.637     raeburn  2285: sub extract_embedded_items {
1.961     raeburn  2286:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2287:     my @state = ();
                   2288:     my %javafiles = (
                   2289:                       codebase => '',
                   2290:                       code => '',
                   2291:                       archive => ''
                   2292:                     );
                   2293:     my %mediafiles = (
                   2294:                       src => '',
                   2295:                       movie => '',
                   2296:                      );
1.648     raeburn  2297:     my $p;
                   2298:     if ($content) {
                   2299:         $p = HTML::LCParser->new($content);
                   2300:     } else {
1.961     raeburn  2301:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2302:     }
1.641     albertel 2303:     while (my $t=$p->get_token()) {
1.640     albertel 2304: 	if ($t->[0] eq 'S') {
                   2305: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2306: 	    push(@state, $tagname);
1.648     raeburn  2307:             if (lc($tagname) eq 'allow') {
                   2308:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2309:             }
1.640     albertel 2310: 	    if (lc($tagname) eq 'img') {
                   2311: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2312: 	    }
1.886     albertel 2313: 	    if (lc($tagname) eq 'a') {
                   2314: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2315: 	    }
1.645     raeburn  2316:             if (lc($tagname) eq 'script') {
                   2317:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2318:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2319:                 } else {
                   2320:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2321:                 }
                   2322:             }
                   2323:             if (lc($tagname) eq 'link') {
                   2324:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2325:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2326:                 }
                   2327:             }
1.640     albertel 2328: 	    if (lc($tagname) eq 'object' ||
                   2329: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2330: 		foreach my $item (keys(%javafiles)) {
                   2331: 		    $javafiles{$item} = '';
                   2332: 		}
                   2333: 	    }
                   2334: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2335: 		my $name = lc($attr->{'name'});
                   2336: 		foreach my $item (keys(%javafiles)) {
                   2337: 		    if ($name eq $item) {
                   2338: 			$javafiles{$item} = $attr->{'value'};
                   2339: 			last;
                   2340: 		    }
                   2341: 		}
                   2342: 		foreach my $item (keys(%mediafiles)) {
                   2343: 		    if ($name eq $item) {
                   2344: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2345: 			last;
                   2346: 		    }
                   2347: 		}
                   2348: 	    }
                   2349: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2350: 		foreach my $item (keys(%javafiles)) {
                   2351: 		    if ($attr->{$item}) {
                   2352: 			$javafiles{$item} = $attr->{$item};
                   2353: 			last;
                   2354: 		    }
                   2355: 		}
                   2356: 		foreach my $item (keys(%mediafiles)) {
                   2357: 		    if ($attr->{$item}) {
                   2358: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2359: 			last;
                   2360: 		    }
                   2361: 		}
                   2362: 	    }
                   2363: 	} elsif ($t->[0] eq 'E') {
                   2364: 	    my ($tagname) = ($t->[1]);
                   2365: 	    if ($javafiles{'codebase'} ne '') {
                   2366: 		$javafiles{'codebase'} .= '/';
                   2367: 	    }  
                   2368: 	    if (lc($tagname) eq 'applet' ||
                   2369: 		lc($tagname) eq 'object' ||
                   2370: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2371: 		) {
                   2372: 		foreach my $item (keys(%javafiles)) {
                   2373: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2374: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2375: 			&add_filetype($allfiles,$file,$item);
                   2376: 		    }
                   2377: 		}
                   2378: 	    } 
                   2379: 	    pop @state;
                   2380: 	}
                   2381:     }
1.637     raeburn  2382:     return 'ok';
                   2383: }
                   2384: 
1.639     albertel 2385: sub add_filetype {
                   2386:     my ($allfiles,$file,$type)=@_;
                   2387:     if (exists($allfiles->{$file})) {
                   2388: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2389: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2390: 	}
                   2391:     } else {
                   2392: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2393:     }
                   2394: }
                   2395: 
1.493     albertel 2396: sub removeuploadedurl {
1.984     neumanie 2397:     my ($url)=@_;	
                   2398:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2399:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2400: }
                   2401: 
                   2402: sub removeuserfile {
                   2403:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2404:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2405:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2406:     if ($result eq 'ok') {	
1.798     raeburn  2407:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2408:             my $metafile = $fname.'.meta';
                   2409:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2410: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2411:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2412:             my $sqlresult = 
1.823     albertel 2413:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2414:                                         'portfolio_metadata',$group,
                   2415:                                         'delete');
1.798     raeburn  2416:         }
                   2417:     }
                   2418:     return $result;
1.257     www      2419: }
1.15      www      2420: 
1.530     albertel 2421: sub mkdiruserfile {
                   2422:     my ($docuname,$docudom,$dir)=@_;
                   2423:     my $home=&homeserver($docuname,$docudom);
                   2424:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2425: }
                   2426: 
1.531     albertel 2427: sub renameuserfile {
                   2428:     my ($docuname,$docudom,$old,$new)=@_;
                   2429:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2430:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2431:                         &escape("$old").':'.&escape("$new"),$home);
                   2432:     if ($result eq 'ok') {
                   2433:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2434:             my $oldmeta = $old.'.meta';
                   2435:             my $newmeta = $new.'.meta';
                   2436:             my $metaresult = 
                   2437:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2438: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2439:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2440:             my $sqlresult = 
1.823     albertel 2441:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2442:                                         'portfolio_metadata',$group,
                   2443:                                         'delete');
1.798     raeburn  2444:         }
                   2445:     }
                   2446:     return $result;
1.531     albertel 2447: }
                   2448: 
1.14      www      2449: # ------------------------------------------------------------------------- Log
                   2450: 
                   2451: sub log {
                   2452:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2453:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2454: }
                   2455: 
                   2456: # ------------------------------------------------------------------ Course Log
1.352     www      2457: #
                   2458: # This routine flushes several buffers of non-mission-critical nature
                   2459: #
1.157     www      2460: 
                   2461: sub flushcourselogs {
1.352     www      2462:     &logthis('Flushing log buffers');
                   2463: #
                   2464: # course logs
                   2465: # This is a log of all transactions in a course, which can be used
                   2466: # for data mining purposes
                   2467: #
                   2468: # It also collects the courseid database, which lists last transaction
                   2469: # times and course titles for all courseids
                   2470: #
                   2471:     my %courseidbuffer=();
1.921     raeburn  2472:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2473:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2474: 		          &escape($courselogs{$crsid}),
                   2475: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2476: 	    delete $courselogs{$crsid};
                   2477:         } else {
                   2478:             &logthis('Failed to flush log buffer for '.$crsid);
                   2479:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2480:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2481:                         " exceeded maximum size, deleting.</font>");
                   2482:                delete $courselogs{$crsid};
                   2483:             }
1.352     www      2484:         }
1.920     raeburn  2485:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2486:             'description' => $coursedescrbuf{$crsid},
                   2487:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2488:             'type'        => $coursetypebuf{$crsid},
                   2489:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2490:         };
1.191     harris41 2491:     }
1.352     www      2492: #
                   2493: # Write course id database (reverse lookup) to homeserver of courses 
                   2494: # Is used in pickcourse
                   2495: #
1.840     albertel 2496:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2497:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2498:                                     $courseidbuffer{$crs_home},
                   2499:                                     $crs_home,'timeonly');
1.352     www      2500:     }
                   2501: #
                   2502: # File accesses
                   2503: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2504: #
1.449     matthew  2505:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2506:         if ($entry =~ /___count$/) {
                   2507:             my ($dom,$name);
1.807     albertel 2508:             ($dom,$name,undef)=
1.811     albertel 2509: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2510:             if (! defined($dom) || $dom eq '' || 
                   2511:                 ! defined($name) || $name eq '') {
1.620     albertel 2512:                 my $cid = $env{'request.course.id'};
                   2513:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2514:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2515:             }
1.450     matthew  2516:             my $value = $accesshash{$entry};
                   2517:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2518:             my %temphash=($url => $value);
1.449     matthew  2519:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2520:             if ($result eq 'ok') {
                   2521:                 delete $accesshash{$entry};
                   2522:             } elsif ($result eq 'unknown_cmd') {
                   2523:                 # Target server has old code running on it.
1.450     matthew  2524:                 my %temphash=($entry => $value);
1.449     matthew  2525:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2526:                     delete $accesshash{$entry};
                   2527:                 }
                   2528:             }
                   2529:         } else {
1.811     albertel 2530:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2531:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2532:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2533:                 delete $accesshash{$entry};
                   2534:             }
1.185     www      2535:         }
1.191     harris41 2536:     }
1.352     www      2537: #
                   2538: # Roles
                   2539: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2540: #
1.800     albertel 2541:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2542:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2543: 	    split(/\:/,$entry);
                   2544:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2545:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2546:                 $rudom,$runame) eq 'ok') {
                   2547: 	    delete $userrolehash{$entry};
                   2548:         }
                   2549:     }
1.662     raeburn  2550: #
                   2551: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2552: #
                   2553:     my %domrolebuffer = ();
                   2554:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2555:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2556:         if ($domrolebuffer{$rudom}) {
                   2557:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2558:                       '='.&escape($domainrolehash{$entry});
                   2559:         } else {
                   2560:             $domrolebuffer{$rudom}.=&escape($entry).
                   2561:                       '='.&escape($domainrolehash{$entry});
                   2562:         }
                   2563:         delete $domainrolehash{$entry};
                   2564:     }
                   2565:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2566: 	my %servers = &get_servers($dom,'library');
                   2567: 	foreach my $tryserver (keys(%servers)) {
                   2568: 	    unless (&reply('domroleput:'.$dom.':'.
                   2569: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2570: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2571: 	    }
1.662     raeburn  2572:         }
                   2573:     }
1.186     www      2574:     $dumpcount++;
1.157     www      2575: }
                   2576: 
                   2577: sub courselog {
                   2578:     my $what=shift;
1.158     www      2579:     $what=time.':'.$what;
1.620     albertel 2580:     unless ($env{'request.course.id'}) { return ''; }
                   2581:     $coursedombuf{$env{'request.course.id'}}=
                   2582:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2583:     $coursenumbuf{$env{'request.course.id'}}=
                   2584:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2585:     $coursehombuf{$env{'request.course.id'}}=
                   2586:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2587:     $coursedescrbuf{$env{'request.course.id'}}=
                   2588:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2589:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2590:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2591:     $courseownerbuf{$env{'request.course.id'}}=
                   2592:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2593:     $coursetypebuf{$env{'request.course.id'}}=
                   2594:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2595:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2596: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2597:     } else {
1.620     albertel 2598: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2599:     }
1.620     albertel 2600:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2601: 	&flushcourselogs();
                   2602:     }
1.158     www      2603: }
                   2604: 
                   2605: sub courseacclog {
                   2606:     my $fnsymb=shift;
1.620     albertel 2607:     unless ($env{'request.course.id'}) { return ''; }
                   2608:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2609:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2610:         $what.=':POST';
1.583     matthew  2611:         # FIXME: Probably ought to escape things....
1.800     albertel 2612: 	foreach my $key (keys(%env)) {
                   2613:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2614:                 my $formitem = $1;
                   2615:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2616:                     $what.=':'.$formitem.'='.$env{$key};
                   2617:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2618:                     $what.=':'.$formitem.'='.$env{$key};
                   2619:                 }
1.158     www      2620:             }
1.191     harris41 2621:         }
1.583     matthew  2622:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2623:         # FIXME: We should not be depending on a form parameter that someone
                   2624:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2625:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2626:             $what.= ':POST';
                   2627:             # FIXME: Probably ought to escape things....
                   2628:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2629:                                  'crsdiscuss') {
1.620     albertel 2630:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2631:             }
                   2632:         }
1.158     www      2633:     }
                   2634:     &courselog($what);
1.149     www      2635: }
                   2636: 
1.185     www      2637: sub countacc {
                   2638:     my $url=&declutter(shift);
1.458     matthew  2639:     return if (! defined($url) || $url eq '');
1.620     albertel 2640:     unless ($env{'request.course.id'}) { return ''; }
                   2641:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2642:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2643:     $accesshash{$key}++;
1.185     www      2644: }
1.349     www      2645: 
1.361     www      2646: sub linklog {
                   2647:     my ($from,$to)=@_;
                   2648:     $from=&declutter($from);
                   2649:     $to=&declutter($to);
                   2650:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2651:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2652: }
                   2653:   
1.349     www      2654: sub userrolelog {
                   2655:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2656:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2657:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2658:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2659:         ($trole=~/^ta/)) {
1.350     www      2660:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2661:        $userrolehash
                   2662:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2663:                     =$tend.':'.$tstart;
1.662     raeburn  2664:     }
1.898     albertel 2665:     if (($env{'request.role'} =~ /dc\./) &&
                   2666: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2667: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2668: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2669:        $userrolehash
                   2670:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2671:                     =$tend.':'.$tstart;
                   2672:     }
1.662     raeburn  2673:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2674:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2675:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2676:         ($trole=~/^sc/)) {
                   2677:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2678:        $domainrolehash
                   2679:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2680:                     = $tend.':'.$tstart;
                   2681:     }
1.351     www      2682: }
                   2683: 
1.957     raeburn  2684: sub courserolelog {
                   2685:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2686:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2687:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2688:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2689:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2690:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2691:             my $cdom = $1;
                   2692:             my $cnum = $2;
                   2693:             my $sec = $3;
                   2694:             my $namespace = 'rolelog';
                   2695:             my %storehash = (
                   2696:                                role    => $trole,
                   2697:                                start   => $tstart,
                   2698:                                end     => $tend,
                   2699:                                selfenroll => $selfenroll,
                   2700:                                context    => $context,
                   2701:                             );
                   2702:             if ($trole eq 'gr') {
                   2703:                 $namespace = 'groupslog';
                   2704:                 $storehash{'group'} = $sec;
                   2705:             } else {
                   2706:                 $storehash{'section'} = $sec;
                   2707:             }
                   2708:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
                   2709:         }
                   2710:     }
                   2711:     return;
                   2712: }
                   2713: 
1.351     www      2714: sub get_course_adv_roles {
1.948     raeburn  2715:     my ($cid,$codes) = @_;
1.620     albertel 2716:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2717:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2718:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2719:     my %nothide=();
1.800     albertel 2720:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2721:         if ($user !~ /:/) {
                   2722: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2723:         } else {
                   2724:             $nothide{$user}=1;
                   2725:         }
1.470     www      2726:     }
1.351     www      2727:     my %returnhash=();
                   2728:     my %dumphash=
                   2729:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2730:     my $now=time;
1.800     albertel 2731:     foreach my $entry (keys %dumphash) {
                   2732: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2733:         if (($tstart) && ($tstart<0)) { next; }
                   2734:         if (($tend) && ($tend<$now)) { next; }
                   2735:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2736:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2737: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2738: 	if ((&privileged($username,$domain)) && 
                   2739: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2740: 	if ($role eq 'cr') { next; }
1.948     raeburn  2741:         if ($codes) {
                   2742:             if ($section) { $role .= ':'.$section; }
                   2743:             if ($returnhash{$role}) {
                   2744:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2745:             } else {
                   2746:                 $returnhash{$role}=$username.':'.$domain;
                   2747:             }
1.351     www      2748:         } else {
1.988     raeburn  2749:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2750:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2751:             if ($returnhash{$key}) {
                   2752: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2753:             } else {
                   2754:                 $returnhash{$key}=$username.':'.$domain;
                   2755:             }
1.351     www      2756:         }
1.948     raeburn  2757:     }
1.400     www      2758:     return %returnhash;
                   2759: }
                   2760: 
                   2761: sub get_my_roles {
1.937     raeburn  2762:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2763:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2764:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2765:     my (%dumphash,%nothide);
1.858     raeburn  2766:     if ($context eq 'userroles') { 
                   2767:         %dumphash = &dump('roles',$udom,$uname);
                   2768:     } else {
                   2769:         %dumphash=
1.400     www      2770:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2771:         if ($hidepriv) {
                   2772:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2773:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2774:                 if ($user !~ /:/) {
                   2775:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2776:                 } else {
                   2777:                     $nothide{$user} = 1;
                   2778:                 }
                   2779:             }
                   2780:         }
1.858     raeburn  2781:     }
1.400     www      2782:     my %returnhash=();
                   2783:     my $now=time;
1.800     albertel 2784:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2785:         my ($role,$tend,$tstart);
                   2786:         if ($context eq 'userroles') {
                   2787: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2788:         } else {
                   2789:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2790:         }
1.400     www      2791:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2792:         my $status = 'active';
1.939     raeburn  2793:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2794:             $status = 'previous';
                   2795:         } 
                   2796:         if (($tstart) && ($now<$tstart)) {
                   2797:             $status = 'future';
                   2798:         }
                   2799:         if (ref($types) eq 'ARRAY') {
                   2800:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2801:                 next;
                   2802:             } 
                   2803:         } else {
                   2804:             if ($status ne 'active') {
                   2805:                 next;
                   2806:             }
                   2807:         }
1.867     raeburn  2808:         my ($rolecode,$username,$domain,$section,$area);
                   2809:         if ($context eq 'userroles') {
                   2810:             ($area,$rolecode) = split(/_/,$entry);
                   2811:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2812:         } else {
                   2813:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2814:         }
1.832     raeburn  2815:         if (ref($roledoms) eq 'ARRAY') {
                   2816:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2817:                 next;
                   2818:             }
                   2819:         }
                   2820:         if (ref($roles) eq 'ARRAY') {
                   2821:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2822:                 if ($role =~ /^cr\//) {
                   2823:                     if (!grep(/^cr$/,@{$roles})) {
                   2824:                         next;
                   2825:                     }
                   2826:                 } else {
                   2827:                     next;
                   2828:                 }
1.832     raeburn  2829:             }
1.867     raeburn  2830:         }
1.937     raeburn  2831:         if ($hidepriv) {
                   2832:             if ((&privileged($username,$domain)) &&
                   2833:                 (!$nothide{$username.':'.$domain})) { 
                   2834:                 next;
                   2835:             }
                   2836:         }
1.933     raeburn  2837:         if ($withsec) {
                   2838:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2839:                 $tstart.':'.$tend;
                   2840:         } else {
                   2841:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2842:         }
1.832     raeburn  2843:     }
1.373     www      2844:     return %returnhash;
1.399     www      2845: }
                   2846: 
                   2847: # ----------------------------------------------------- Frontpage Announcements
                   2848: #
                   2849: #
                   2850: 
                   2851: sub postannounce {
                   2852:     my ($server,$text)=@_;
1.844     albertel 2853:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2854:     unless ($text=~/\w/) { $text=''; }
                   2855:     return &reply('setannounce:'.&escape($text),$server);
                   2856: }
                   2857: 
                   2858: sub getannounce {
1.448     albertel 2859: 
                   2860:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2861: 	my $announcement='';
1.800     albertel 2862: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2863: 	close($fh);
1.399     www      2864: 	if ($announcement=~/\w/) { 
                   2865: 	    return 
                   2866:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2867:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2868: 	} else {
                   2869: 	    return '';
                   2870: 	}
                   2871:     } else {
                   2872: 	return '';
                   2873:     }
1.351     www      2874: }
1.353     www      2875: 
                   2876: # ---------------------------------------------------------- Course ID routines
                   2877: # Deal with domain's nohist_courseid.db files
                   2878: #
                   2879: 
                   2880: sub courseidput {
1.921     raeburn  2881:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2882:     my $outcome;
                   2883:     if ($caller eq 'timeonly') {
                   2884:         my $cids = '';
                   2885:         foreach my $item (keys(%$storehash)) {
                   2886:             $cids.=&escape($item).'&';
                   2887:         }
                   2888:         $cids=~s/\&$//;
                   2889:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2890:                           $coursehome);       
                   2891:     } else {
                   2892:         my $items = '';
                   2893:         foreach my $item (keys(%$storehash)) {
                   2894:             $items.= &escape($item).'='.
                   2895:                      &freeze_escape($$storehash{$item}).'&';
                   2896:         }
                   2897:         $items=~s/\&$//;
                   2898:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2899:                           $coursehome);
1.918     raeburn  2900:     }
                   2901:     if ($outcome eq 'unknown_cmd') {
                   2902:         my $what;
                   2903:         foreach my $cid (keys(%$storehash)) {
                   2904:             $what .= &escape($cid).'=';
1.921     raeburn  2905:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2906:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2907:             }
                   2908:             $what =~ s/\:$/&/;
                   2909:         }
                   2910:         $what =~ s/\&$//;  
                   2911:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2912:     } else {
                   2913:         return $outcome;
                   2914:     }
1.353     www      2915: }
                   2916: 
                   2917: sub courseiddump {
1.921     raeburn  2918:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2919:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2920:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2921:     my $as_hash = 1;
                   2922:     my %returnhash;
                   2923:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2924:     my %libserv = &all_library();
                   2925:     foreach my $tryserver (keys(%libserv)) {
                   2926:         if ( (  $hostidflag == 1 
                   2927: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2928: 	     || (!defined($hostidflag)) ) {
                   2929: 
1.918     raeburn  2930: 	    if (($domfilter eq '') ||
                   2931: 		(&host_domain($tryserver) eq $domfilter)) {
                   2932:                 my $rep = 
                   2933:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2934:                          $sincefilter.':'.&escape($descfilter).':'.
                   2935:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2936:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2937:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2938:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2939:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2940:                 my @pairs=split(/\&/,$rep);
                   2941:                 foreach my $item (@pairs) {
                   2942:                     my ($key,$value)=split(/\=/,$item,2);
                   2943:                     $key = &unescape($key);
                   2944:                     next if ($key =~ /^error: 2 /);
                   2945:                     my $result = &thaw_unescape($value);
                   2946:                     if (ref($result) eq 'HASH') {
                   2947:                         $returnhash{$key}=$result;
                   2948:                     } else {
1.921     raeburn  2949:                         my @responses = split(/:/,$value);
                   2950:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2951:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2952:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2953:                         }
                   2954:                     } 
1.353     www      2955:                 }
                   2956:             }
                   2957:         }
                   2958:     }
                   2959:     return %returnhash;
                   2960: }
                   2961: 
1.658     raeburn  2962: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2963: 
                   2964: sub dcmailput {
1.685     raeburn  2965:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2966:     my $status = &Apache::lonnet::critical(
1.740     www      2967:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2968:        &escape($message),$server);
1.662     raeburn  2969:     return $status;
                   2970: }
                   2971: 
1.658     raeburn  2972: sub dcmaildump {
                   2973:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2974:     my %returnhash=();
1.846     albertel 2975: 
                   2976:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2977:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2978:                                                          &escape($enddate).':';
                   2979: 	my @esc_senders=map { &escape($_)} @$senders;
                   2980: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2981: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2982:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2983:             if (($key) && ($value)) {
                   2984:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2985:             }
                   2986:         }
                   2987:     }
                   2988:     return %returnhash;
                   2989: }
1.662     raeburn  2990: # ---------------------------------------------------------- Domain roles
                   2991: 
                   2992: sub get_domain_roles {
                   2993:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2994:     if (undef($startdate) || $startdate eq '') {
                   2995:         $startdate = '.';
                   2996:     }
                   2997:     if (undef($enddate) || $enddate eq '') {
                   2998:         $enddate = '.';
                   2999:     }
1.922     raeburn  3000:     my $rolelist;
                   3001:     if (ref($roles) eq 'ARRAY') {
                   3002:         $rolelist = join(':',@{$roles});
                   3003:     }
1.662     raeburn  3004:     my %personnel = ();
1.841     albertel 3005: 
                   3006:     my %servers = &get_servers($dom,'library');
                   3007:     foreach my $tryserver (keys(%servers)) {
                   3008: 	%{$personnel{$tryserver}}=();
                   3009: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3010: 					    &escape($startdate).':'.
                   3011: 					    &escape($enddate).':'.
                   3012: 					    &escape($rolelist), $tryserver))) {
                   3013: 	    my ($key,$value) = split(/\=/,$line,2);
                   3014: 	    if (($key) && ($value)) {
                   3015: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3016: 	    }
                   3017: 	}
1.662     raeburn  3018:     }
                   3019:     return %personnel;
                   3020: }
1.658     raeburn  3021: 
1.149     www      3022: # ----------------------------------------------------------- Check out an item
                   3023: 
1.504     albertel 3024: sub get_first_access {
                   3025:     my ($type,$argsymb)=@_;
1.790     albertel 3026:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3027:     if ($argsymb) { $symb=$argsymb; }
                   3028:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3029:     if ($type eq 'course') {
                   3030: 	$res='course';
                   3031:     } elsif ($type eq 'map') {
1.588     albertel 3032: 	$res=&symbread($map);
                   3033:     } else {
                   3034: 	$res=$symb;
                   3035:     }
                   3036:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3037:     return $times{"$courseid\0$res"};
1.504     albertel 3038: }
                   3039: 
                   3040: sub set_first_access {
                   3041:     my ($type)=@_;
1.790     albertel 3042:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3043:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3044:     if ($type eq 'course') {
                   3045: 	$res='course';
                   3046:     } elsif ($type eq 'map') {
1.588     albertel 3047: 	$res=&symbread($map);
                   3048:     } else {
                   3049: 	$res=$symb;
                   3050:     }
                   3051:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3052:     if (!$firstaccess) {
1.588     albertel 3053: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3054:     }
                   3055:     return 'already_set';
1.504     albertel 3056: }
                   3057: 
1.149     www      3058: sub checkout {
                   3059:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3060:     my $now=time;
                   3061:     my $lonhost=$perlvar{'lonHostID'};
                   3062:     my $infostr=&escape(
1.234     www      3063:                  'CHECKOUTTOKEN&'.
1.149     www      3064:                  $tuname.'&'.
                   3065:                  $tudom.'&'.
                   3066:                  $tcrsid.'&'.
                   3067:                  $symb.'&'.
                   3068: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3069:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3070:     if ($token=~/^error\:/) { 
1.672     albertel 3071:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3072:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3073:                  "</font>");
                   3074:         return ''; 
                   3075:     }
                   3076: 
1.149     www      3077:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3078:     $token=~tr/a-z/A-Z/;
                   3079: 
1.153     www      3080:     my %infohash=('resource.0.outtoken' => $token,
                   3081:                   'resource.0.checkouttime' => $now,
                   3082:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3083: 
                   3084:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3085:        return '';
1.151     www      3086:     } else {
1.672     albertel 3087:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3088:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3089:                  "</font>");
1.149     www      3090:     }    
                   3091: 
                   3092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3093:                          &escape('Checkout '.$infostr.' - '.
                   3094:                                                  $token)) ne 'ok') {
                   3095: 	return '';
1.151     www      3096:     } else {
1.672     albertel 3097:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3098:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3099:                  "</font>");
1.149     www      3100:     }
1.151     www      3101:     return $token;
1.149     www      3102: }
                   3103: 
                   3104: # ------------------------------------------------------------ Check in an item
                   3105: 
                   3106: sub checkin {
                   3107:     my $token=shift;
1.150     www      3108:     my $now=time;
                   3109:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3110:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3111:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3112:     $dtoken=~s/\W/\_/g;
1.234     www      3113:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3114:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3115: 
1.154     www      3116:     unless (($tuname) && ($tudom)) {
                   3117:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3118:         return '';
                   3119:     }
                   3120:     
                   3121:     unless (&allowed('mgr',$tcrsid)) {
                   3122:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3123:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3124:         return '';
                   3125:     }
                   3126: 
1.153     www      3127:     my %infohash=('resource.0.intoken' => $token,
                   3128:                   'resource.0.checkintime' => $now,
                   3129:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3130: 
                   3131:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3132:        return '';
                   3133:     }    
                   3134: 
                   3135:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3136:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3137: 	return '';
                   3138:     }
                   3139: 
                   3140:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3141: }
                   3142: 
                   3143: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3144: 
                   3145: sub expirespread {
                   3146:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3147:     my $cid=$env{'request.course.id'}; 
1.110     www      3148:     if ($cid) {
                   3149:        my $now=time;
                   3150:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3151:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3152:                             $env{'course.'.$cid.'.num'}.
1.110     www      3153: 	        	    ':nohist_expirationdates:'.
                   3154:                             &escape($key).'='.$now,
1.620     albertel 3155:                             $env{'course.'.$cid.'.home'})
1.110     www      3156:     }
                   3157:     return 'ok';
1.14      www      3158: }
                   3159: 
1.109     www      3160: # ----------------------------------------------------- Devalidate Spreadsheets
                   3161: 
                   3162: sub devalidate {
1.325     www      3163:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3164:     my $cid=$env{'request.course.id'}; 
1.109     www      3165:     if ($cid) {
1.391     matthew  3166:         # delete the stored spreadsheets for
                   3167:         # - the student level sheet of this user in course's homespace
                   3168:         # - the assessment level sheet for this resource 
                   3169:         #   for this user in user's homespace
1.553     albertel 3170: 	# - current conditional state info
1.325     www      3171: 	my $key=$uname.':'.$udom.':';
1.109     www      3172:         my $status=
1.299     matthew  3173: 	    &del('nohist_calculatedsheets',
1.391     matthew  3174: 		 [$key.'studentcalc:'],
1.620     albertel 3175: 		 $env{'course.'.$cid.'.domain'},
                   3176: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3177: 		.' '.
                   3178: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3179: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3180:         unless ($status eq 'ok ok') {
                   3181:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3182:                     $uname.' at '.$udom.' for '.
1.109     www      3183: 		    $symb.': '.$status);
1.133     albertel 3184:         }
1.553     albertel 3185: 	&delenv('user.state.'.$cid);
1.109     www      3186:     }
                   3187: }
                   3188: 
1.265     albertel 3189: sub get_scalar {
                   3190:     my ($string,$end) = @_;
                   3191:     my $value;
                   3192:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3193: 	$value = $1;
                   3194:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3195: 	$value = $1;
                   3196:     }
                   3197:     return &unescape($value);
                   3198: }
                   3199: 
                   3200: sub array2str {
                   3201:   my (@array) = @_;
                   3202:   my $result=&arrayref2str(\@array);
                   3203:   $result=~s/^__ARRAY_REF__//;
                   3204:   $result=~s/__END_ARRAY_REF__$//;
                   3205:   return $result;
                   3206: }
                   3207: 
1.204     albertel 3208: sub arrayref2str {
                   3209:   my ($arrayref) = @_;
1.265     albertel 3210:   my $result='__ARRAY_REF__';
1.204     albertel 3211:   foreach my $elem (@$arrayref) {
1.265     albertel 3212:     if(ref($elem) eq 'ARRAY') {
                   3213:       $result.=&arrayref2str($elem).'&';
                   3214:     } elsif(ref($elem) eq 'HASH') {
                   3215:       $result.=&hashref2str($elem).'&';
                   3216:     } elsif(ref($elem)) {
                   3217:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3218:     } else {
                   3219:       $result.=&escape($elem).'&';
                   3220:     }
                   3221:   }
                   3222:   $result=~s/\&$//;
1.265     albertel 3223:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3224:   return $result;
                   3225: }
                   3226: 
1.168     albertel 3227: sub hash2str {
1.204     albertel 3228:   my (%hash) = @_;
                   3229:   my $result=&hashref2str(\%hash);
1.265     albertel 3230:   $result=~s/^__HASH_REF__//;
                   3231:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3232:   return $result;
                   3233: }
                   3234: 
                   3235: sub hashref2str {
                   3236:   my ($hashref)=@_;
1.265     albertel 3237:   my $result='__HASH_REF__';
1.800     albertel 3238:   foreach my $key (sort(keys(%$hashref))) {
                   3239:     if (ref($key) eq 'ARRAY') {
                   3240:       $result.=&arrayref2str($key).'=';
                   3241:     } elsif (ref($key) eq 'HASH') {
                   3242:       $result.=&hashref2str($key).'=';
                   3243:     } elsif (ref($key)) {
1.265     albertel 3244:       $result.='=';
1.800     albertel 3245:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3246:     } else {
1.800     albertel 3247: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3248:     }
                   3249: 
1.800     albertel 3250:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3251:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3252:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3253:       $result.=&hashref2str($hashref->{$key}).'&';
                   3254:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3255:        $result.='&';
1.800     albertel 3256:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3257:     } else {
1.800     albertel 3258:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3259:     }
                   3260:   }
1.168     albertel 3261:   $result=~s/\&$//;
1.265     albertel 3262:   $result .= '__END_HASH_REF__';
1.168     albertel 3263:   return $result;
                   3264: }
                   3265: 
                   3266: sub str2hash {
1.265     albertel 3267:     my ($string)=@_;
                   3268:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3269:     return %$hash;
                   3270: }
                   3271: 
                   3272: sub str2hashref {
1.168     albertel 3273:   my ($string) = @_;
1.265     albertel 3274: 
                   3275:   my %hash;
                   3276: 
                   3277:   if($string !~ /^__HASH_REF__/) {
                   3278:       if (! ($string eq '' || !defined($string))) {
                   3279: 	  $hash{'error'}='Not hash reference';
                   3280:       }
                   3281:       return (\%hash, $string);
                   3282:   }
                   3283: 
                   3284:   $string =~ s/^__HASH_REF__//;
                   3285: 
                   3286:   while($string !~ /^__END_HASH_REF__/) {
                   3287:       #key
                   3288:       my $key='';
                   3289:       if($string =~ /^__HASH_REF__/) {
                   3290:           ($key, $string)=&str2hashref($string);
                   3291:           if(defined($key->{'error'})) {
                   3292:               $hash{'error'}='Bad data';
                   3293:               return (\%hash, $string);
                   3294:           }
                   3295:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3296:           ($key, $string)=&str2arrayref($string);
                   3297:           if($key->[0] eq 'Array reference error') {
                   3298:               $hash{'error'}='Bad data';
                   3299:               return (\%hash, $string);
                   3300:           }
                   3301:       } else {
                   3302:           $string =~ s/^(.*?)=//;
1.267     albertel 3303: 	  $key=&unescape($1);
1.265     albertel 3304:       }
                   3305:       $string =~ s/^=//;
                   3306: 
                   3307:       #value
                   3308:       my $value='';
                   3309:       if($string =~ /^__HASH_REF__/) {
                   3310:           ($value, $string)=&str2hashref($string);
                   3311:           if(defined($value->{'error'})) {
                   3312:               $hash{'error'}='Bad data';
                   3313:               return (\%hash, $string);
                   3314:           }
                   3315:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3316:           ($value, $string)=&str2arrayref($string);
                   3317:           if($value->[0] eq 'Array reference error') {
                   3318:               $hash{'error'}='Bad data';
                   3319:               return (\%hash, $string);
                   3320:           }
                   3321:       } else {
                   3322: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3323:       }
                   3324:       $string =~ s/^&//;
                   3325: 
                   3326:       $hash{$key}=$value;
1.204     albertel 3327:   }
1.265     albertel 3328: 
                   3329:   $string =~ s/^__END_HASH_REF__//;
                   3330: 
                   3331:   return (\%hash, $string);
1.204     albertel 3332: }
                   3333: 
                   3334: sub str2array {
1.265     albertel 3335:     my ($string)=@_;
                   3336:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3337:     return @$array;
                   3338: }
                   3339: 
                   3340: sub str2arrayref {
1.204     albertel 3341:   my ($string) = @_;
1.265     albertel 3342:   my @array;
                   3343: 
                   3344:   if($string !~ /^__ARRAY_REF__/) {
                   3345:       if (! ($string eq '' || !defined($string))) {
                   3346: 	  $array[0]='Array reference error';
                   3347:       }
                   3348:       return (\@array, $string);
                   3349:   }
                   3350: 
                   3351:   $string =~ s/^__ARRAY_REF__//;
                   3352: 
                   3353:   while($string !~ /^__END_ARRAY_REF__/) {
                   3354:       my $value='';
                   3355:       if($string =~ /^__HASH_REF__/) {
                   3356:           ($value, $string)=&str2hashref($string);
                   3357:           if(defined($value->{'error'})) {
                   3358:               $array[0] ='Array reference error';
                   3359:               return (\@array, $string);
                   3360:           }
                   3361:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3362:           ($value, $string)=&str2arrayref($string);
                   3363:           if($value->[0] eq 'Array reference error') {
                   3364:               $array[0] ='Array reference error';
                   3365:               return (\@array, $string);
                   3366:           }
                   3367:       } else {
                   3368: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3369:       }
                   3370:       $string =~ s/^&//;
                   3371: 
                   3372:       push(@array, $value);
1.191     harris41 3373:   }
1.265     albertel 3374: 
                   3375:   $string =~ s/^__END_ARRAY_REF__//;
                   3376: 
                   3377:   return (\@array, $string);
1.168     albertel 3378: }
                   3379: 
1.167     albertel 3380: # -------------------------------------------------------------------Temp Store
                   3381: 
1.168     albertel 3382: sub tmpreset {
                   3383:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3384:   if (!$symb) {
                   3385:     $symb=&symbread();
1.620     albertel 3386:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3387:   }
                   3388:   $symb=escape($symb);
                   3389: 
1.620     albertel 3390:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3391:   $namespace=~s/\//\_/g;
                   3392:   $namespace=~s/\W//g;
                   3393: 
1.620     albertel 3394:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3395:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3396:   if ($domain eq 'public' && $stuname eq 'public') {
                   3397:       $stuname=$ENV{'REMOTE_ADDR'};
                   3398:   }
1.168     albertel 3399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3400:   my %hash;
                   3401:   if (tie(%hash,'GDBM_File',
                   3402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3403: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3404:     foreach my $key (keys %hash) {
1.180     albertel 3405:       if ($key=~ /:$symb/) {
1.168     albertel 3406: 	delete($hash{$key});
                   3407:       }
                   3408:     }
                   3409:   }
                   3410: }
                   3411: 
1.167     albertel 3412: sub tmpstore {
1.168     albertel 3413:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3414: 
                   3415:   if (!$symb) {
                   3416:     $symb=&symbread();
1.620     albertel 3417:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3418:   }
                   3419:   $symb=escape($symb);
                   3420: 
                   3421:   if (!$namespace) {
                   3422:     # I don't think we would ever want to store this for a course.
                   3423:     # it seems this will only be used if we don't have a course.
1.620     albertel 3424:     #$namespace=$env{'request.course.id'};
1.168     albertel 3425:     #if (!$namespace) {
1.620     albertel 3426:       $namespace=$env{'request.state'};
1.168     albertel 3427:     #}
                   3428:   }
                   3429:   $namespace=~s/\//\_/g;
                   3430:   $namespace=~s/\W//g;
1.620     albertel 3431:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3432:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3433:   if ($domain eq 'public' && $stuname eq 'public') {
                   3434:       $stuname=$ENV{'REMOTE_ADDR'};
                   3435:   }
1.168     albertel 3436:   my $now=time;
                   3437:   my %hash;
                   3438:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3439:   if (tie(%hash,'GDBM_File',
                   3440: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3441: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3442:     $hash{"version:$symb"}++;
                   3443:     my $version=$hash{"version:$symb"};
                   3444:     my $allkeys=''; 
                   3445:     foreach my $key (keys(%$storehash)) {
                   3446:       $allkeys.=$key.':';
1.591     albertel 3447:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3448:     }
                   3449:     $hash{"$version:$symb:timestamp"}=$now;
                   3450:     $allkeys.='timestamp';
                   3451:     $hash{"$version:keys:$symb"}=$allkeys;
                   3452:     if (untie(%hash)) {
                   3453:       return 'ok';
                   3454:     } else {
                   3455:       return "error:$!";
                   3456:     }
                   3457:   } else {
                   3458:     return "error:$!";
                   3459:   }
                   3460: }
1.167     albertel 3461: 
1.168     albertel 3462: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3463: 
1.168     albertel 3464: sub tmprestore {
                   3465:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3466: 
1.168     albertel 3467:   if (!$symb) {
                   3468:     $symb=&symbread();
1.620     albertel 3469:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3470:   }
                   3471:   $symb=escape($symb);
                   3472: 
1.620     albertel 3473:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3474: 
1.620     albertel 3475:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3476:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3477:   if ($domain eq 'public' && $stuname eq 'public') {
                   3478:       $stuname=$ENV{'REMOTE_ADDR'};
                   3479:   }
1.168     albertel 3480:   my %returnhash;
                   3481:   $namespace=~s/\//\_/g;
                   3482:   $namespace=~s/\W//g;
                   3483:   my %hash;
                   3484:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3485:   if (tie(%hash,'GDBM_File',
                   3486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3487: 	  &GDBM_READER(),0640)) {
1.168     albertel 3488:     my $version=$hash{"version:$symb"};
                   3489:     $returnhash{'version'}=$version;
                   3490:     my $scope;
                   3491:     for ($scope=1;$scope<=$version;$scope++) {
                   3492:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3493:       my @keys=split(/:/,$vkeys);
                   3494:       my $key;
                   3495:       $returnhash{"$scope:keys"}=$vkeys;
                   3496:       foreach $key (@keys) {
1.591     albertel 3497: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3498: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3499:       }
                   3500:     }
1.168     albertel 3501:     if (!(untie(%hash))) {
                   3502:       return "error:$!";
                   3503:     }
                   3504:   } else {
                   3505:     return "error:$!";
                   3506:   }
                   3507:   return %returnhash;
1.167     albertel 3508: }
                   3509: 
1.9       www      3510: # ----------------------------------------------------------------------- Store
                   3511: 
                   3512: sub store {
1.124     www      3513:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3514:     my $home='';
                   3515: 
1.168     albertel 3516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3517: 
1.213     www      3518:     $symb=&symbclean($symb);
1.122     albertel 3519:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3520: 
1.620     albertel 3521:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3522:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3523: 
                   3524:     &devalidate($symb,$stuname,$domain);
1.109     www      3525: 
                   3526:     $symb=escape($symb);
1.187     www      3527:     if (!$namespace) { 
1.620     albertel 3528:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3529:           return ''; 
                   3530:        } 
                   3531:     }
1.620     albertel 3532:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3533: 
                   3534:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3535:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3536: 
1.12      www      3537:     my $namevalue='';
1.800     albertel 3538:     foreach my $key (keys(%$storehash)) {
                   3539:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3540:     }
1.12      www      3541:     $namevalue=~s/\&$//;
1.187     www      3542:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3543:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3544: }
                   3545: 
1.47      www      3546: # -------------------------------------------------------------- Critical Store
                   3547: 
                   3548: sub cstore {
1.124     www      3549:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3550:     my $home='';
                   3551: 
1.168     albertel 3552:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3553: 
1.213     www      3554:     $symb=&symbclean($symb);
1.122     albertel 3555:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3556: 
1.620     albertel 3557:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3558:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3559: 
                   3560:     &devalidate($symb,$stuname,$domain);
1.109     www      3561: 
                   3562:     $symb=escape($symb);
1.187     www      3563:     if (!$namespace) { 
1.620     albertel 3564:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3565:           return ''; 
                   3566:        } 
                   3567:     }
1.620     albertel 3568:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3569: 
                   3570:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3571:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3572: 
1.47      www      3573:     my $namevalue='';
1.800     albertel 3574:     foreach my $key (keys(%$storehash)) {
                   3575:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3576:     }
1.47      www      3577:     $namevalue=~s/\&$//;
1.187     www      3578:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3579:     return critical
                   3580:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3581: }
                   3582: 
1.9       www      3583: # --------------------------------------------------------------------- Restore
                   3584: 
                   3585: sub restore {
1.124     www      3586:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3587:     my $home='';
                   3588: 
1.168     albertel 3589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3590: 
1.122     albertel 3591:     if (!$symb) {
                   3592:       unless ($symb=escape(&symbread())) { return ''; }
                   3593:     } else {
1.213     www      3594:       $symb=&escape(&symbclean($symb));
1.122     albertel 3595:     }
1.188     www      3596:     if (!$namespace) { 
1.620     albertel 3597:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3598:           return ''; 
                   3599:        } 
                   3600:     }
1.620     albertel 3601:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3602:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3603:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3604:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3605: 
1.12      www      3606:     my %returnhash=();
1.800     albertel 3607:     foreach my $line (split(/\&/,$answer)) {
                   3608: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3609:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3610:     }
1.75      www      3611:     my $version;
                   3612:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3613:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3614:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3615:        }
1.75      www      3616:     }
1.13      www      3617:     return %returnhash;
1.34      www      3618: }
                   3619: 
                   3620: # ---------------------------------------------------------- Course Description
                   3621: 
                   3622: sub coursedescription {
1.731     albertel 3623:     my ($courseid,$args)=@_;
1.34      www      3624:     $courseid=~s/^\///;
1.49      www      3625:     $courseid=~s/\_/\//g;
1.34      www      3626:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3627:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3628:     my $normalid=$cdomain.'_'.$cnum;
                   3629:     # need to always cache even if we get errors otherwise we keep 
                   3630:     # trying and trying and trying to get the course description.
                   3631:     my %envhash=();
                   3632:     my %returnhash=();
1.731     albertel 3633:     
                   3634:     my $expiretime=600;
                   3635:     if ($env{'request.course.id'} eq $normalid) {
                   3636: 	$expiretime=120;
                   3637:     }
                   3638: 
                   3639:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3640:     if (!$args->{'freshen_cache'}
                   3641: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3642: 	foreach my $key (keys(%env)) {
                   3643: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3644: 	    my ($setting) = $1;
                   3645: 	    $returnhash{$setting} = $env{$key};
                   3646: 	}
                   3647: 	return %returnhash;
                   3648:     }
                   3649: 
                   3650:     # get the data agin
                   3651:     if (!$args->{'one_time'}) {
                   3652: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3653:     }
1.811     albertel 3654: 
1.34      www      3655:     if ($chome ne 'no_host') {
1.302     albertel 3656:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3657:        if (!exists($returnhash{'con_lost'})) {
                   3658:            $returnhash{'home'}= $chome;
                   3659: 	   $returnhash{'domain'} = $cdomain;
                   3660: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3661:            if (!defined($returnhash{'type'})) {
                   3662:                $returnhash{'type'} = 'Course';
                   3663:            }
1.130     albertel 3664:            while (my ($name,$value) = each %returnhash) {
1.53      www      3665:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3666:            }
1.270     www      3667:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3668:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3669: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3670:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3671:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3672:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3673:        }
                   3674:     }
1.731     albertel 3675:     if (!$args->{'one_time'}) {
1.949     raeburn  3676: 	&appenv(\%envhash);
1.731     albertel 3677:     }
1.302     albertel 3678:     return %returnhash;
1.461     www      3679: }
                   3680: 
                   3681: # -------------------------------------------------See if a user is privileged
                   3682: 
                   3683: sub privileged {
                   3684:     my ($username,$domain)=@_;
                   3685:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3686: 			&homeserver($username,$domain));
                   3687:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3688:     my $now=time;
                   3689:     if ($rolesdump ne '') {
1.800     albertel 3690:         foreach my $entry (split(/&/,$rolesdump)) {
                   3691: 	    if ($entry!~/^rolesdef_/) {
                   3692: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3693: 		$area=~s/\_\w\w$//;
                   3694: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3695: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3696: 		    my $active=1;
                   3697: 		    if ($tend) {
                   3698: 			if ($tend<$now) { $active=0; }
                   3699: 		    }
                   3700: 		    if ($tstart) {
                   3701: 			if ($tstart>$now) { $active=0; }
                   3702: 		    }
                   3703: 		    if ($active) { return 1; }
                   3704: 		}
                   3705: 	    }
                   3706: 	}
                   3707:     }
                   3708:     return 0;
1.9       www      3709: }
1.1       albertel 3710: 
1.103     harris41 3711: # -------------------------------------------------------- Get user privileges
1.11      www      3712: 
                   3713: sub rolesinit {
                   3714:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3715:     my %userroles;
1.11      www      3716:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3717:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3718:     my %allroles=();
1.678     raeburn  3719:     my %allgroups=();   
1.11      www      3720:     my $now=time;
1.966     raeburn  3721:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3722:     my $group_privs;
1.11      www      3723: 
                   3724:     if ($rolesdump ne '') {
1.800     albertel 3725:         foreach my $entry (split(/&/,$rolesdump)) {
                   3726: 	  if ($entry!~/^rolesdef_/) {
                   3727:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3728: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3729:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3730: 	    if ($role=~/^cr/) { 
1.807     albertel 3731: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3732: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3733: 		    ($tend,$tstart)=split('_',$trest);
                   3734: 		} else {
                   3735: 		    $trole=$role;
                   3736: 		}
1.678     raeburn  3737:             } elsif ($role =~ m|^gr/|) {
                   3738:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3739:                 ($trole,$group_privs) = split(/\//,$trole);
                   3740:                 $group_privs = &unescape($group_privs);
1.587     albertel 3741: 	    } else {
                   3742: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3743: 	    }
1.743     albertel 3744: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3745: 					 $username);
                   3746: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3747:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3748:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3749:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3750: 		my $spec=$trole.'.'.$area;
                   3751: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3752: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3753:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3754:                 } elsif ($trole eq 'gr') {
                   3755:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3756: 		} else {
1.567     raeburn  3757:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3758: 		}
1.12      www      3759:             }
1.662     raeburn  3760:           }
1.191     harris41 3761:         }
1.743     albertel 3762:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3763:         $userroles{'user.adv'}    = $adv;
                   3764: 	$userroles{'user.author'} = $author;
1.620     albertel 3765:         $env{'user.adv'}=$adv;
1.11      www      3766:     }
1.743     albertel 3767:     return \%userroles;  
1.11      www      3768: }
                   3769: 
1.567     raeburn  3770: sub set_arearole {
                   3771:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3772: # log the associated role with the area
                   3773:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3774:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3775: }
                   3776: 
                   3777: sub custom_roleprivs {
                   3778:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3779:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3780:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3781:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3782:         my ($rdummy,$roledef)=
                   3783:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3784:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3785:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3786:             if (defined($syspriv)) {
                   3787:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3788:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3789:             }
                   3790:             if ($tdomain ne '') {
                   3791:                 if (defined($dompriv)) {
                   3792:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3793:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3794:                 }
                   3795:                 if (($trest ne '') && (defined($coursepriv))) {
                   3796:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3797:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3798:                 }
                   3799:             }
                   3800:         }
                   3801:     }
                   3802: }
                   3803: 
1.678     raeburn  3804: sub group_roleprivs {
                   3805:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3806:     my $access = 1;
                   3807:     my $now = time;
                   3808:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3809:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3810:     if ($access) {
1.811     albertel 3811:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3812:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3813:     }
                   3814: }
1.567     raeburn  3815: 
                   3816: sub standard_roleprivs {
                   3817:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3818:     if (defined($pr{$trole.':s'})) {
                   3819:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3820:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3821:     }
                   3822:     if ($tdomain ne '') {
                   3823:         if (defined($pr{$trole.':d'})) {
                   3824:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3825:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3826:         }
                   3827:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3828:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3829:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3830:         }
                   3831:     }
                   3832: }
                   3833: 
                   3834: sub set_userprivs {
1.678     raeburn  3835:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3836:     my $author=0;
                   3837:     my $adv=0;
1.678     raeburn  3838:     my %grouproles = ();
                   3839:     if (keys(%{$allgroups}) > 0) {
                   3840:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3841:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3842:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3843:                 $trole = $1;
                   3844:                 $area = $2;
1.681     raeburn  3845:                 $sec = $3;
                   3846:                 $extendedarea = $area.$sec;
                   3847:                 if (exists($$allgroups{$area})) {
                   3848:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3849:                         my $spec = $trole.'.'.$extendedarea;
                   3850:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3851:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3852:                     }
                   3853:                 }
                   3854:             }
                   3855:         }
                   3856:     }
1.800     albertel 3857:     foreach my $group (keys(%grouproles)) {
                   3858:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3859:     }
1.800     albertel 3860:     foreach my $role (keys(%{$allroles})) {
                   3861:         my %thesepriv;
1.941     raeburn  3862:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3863:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3864:             if ($item ne '') {
                   3865:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3866:                 if ($restrictions eq '') {
                   3867:                     $thesepriv{$privilege}='F';
                   3868:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3869:                     $thesepriv{$privilege}.=$restrictions;
                   3870:                 }
                   3871:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3872:             }
                   3873:         }
                   3874:         my $thesestr='';
1.800     albertel 3875:         foreach my $priv (keys(%thesepriv)) {
                   3876: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3877: 	}
                   3878:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3879:     }
                   3880:     return ($author,$adv);
                   3881: }
                   3882: 
1.12      www      3883: # --------------------------------------------------------------- get interface
                   3884: 
                   3885: sub get {
1.131     albertel 3886:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3887:    my $items='';
1.800     albertel 3888:    foreach my $item (@$storearr) {
                   3889:        $items.=&escape($item).'&';
1.191     harris41 3890:    }
1.12      www      3891:    $items=~s/\&$//;
1.620     albertel 3892:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3893:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3894:    my $uhome=&homeserver($uname,$udomain);
                   3895: 
1.133     albertel 3896:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3897:    my @pairs=split(/\&/,$rep);
1.273     albertel 3898:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3899:      return @pairs;
                   3900:    }
1.15      www      3901:    my %returnhash=();
1.42      www      3902:    my $i=0;
1.800     albertel 3903:    foreach my $item (@$storearr) {
                   3904:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3905:       $i++;
1.191     harris41 3906:    }
1.15      www      3907:    return %returnhash;
1.27      www      3908: }
                   3909: 
                   3910: # --------------------------------------------------------------- del interface
                   3911: 
                   3912: sub del {
1.133     albertel 3913:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3914:    my $items='';
1.800     albertel 3915:    foreach my $item (@$storearr) {
                   3916:        $items.=&escape($item).'&';
1.191     harris41 3917:    }
1.984     neumanie 3918: 
1.27      www      3919:    $items=~s/\&$//;
1.620     albertel 3920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3921:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3922:    my $uhome=&homeserver($uname,$udomain);
                   3923:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3924: }
                   3925: 
                   3926: # -------------------------------------------------------------- dump interface
                   3927: 
                   3928: sub dump {
1.755     albertel 3929:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3930:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3931:     if (!$uname) { $uname=$env{'user.name'}; }
                   3932:     my $uhome=&homeserver($uname,$udomain);
                   3933:     if ($regexp) {
                   3934: 	$regexp=&escape($regexp);
                   3935:     } else {
                   3936: 	$regexp='.';
                   3937:     }
                   3938:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3939:     my @pairs=split(/\&/,$rep);
                   3940:     my %returnhash=();
                   3941:     foreach my $item (@pairs) {
                   3942: 	my ($key,$value)=split(/=/,$item,2);
                   3943: 	$key = &unescape($key);
                   3944: 	next if ($key =~ /^error: 2 /);
                   3945: 	$returnhash{$key}=&thaw_unescape($value);
                   3946:     }
                   3947:     return %returnhash;
1.407     www      3948: }
                   3949: 
1.717     albertel 3950: # --------------------------------------------------------- dumpstore interface
                   3951: 
                   3952: sub dumpstore {
                   3953:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3954:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3955:    if (!$uname) { $uname=$env{'user.name'}; }
                   3956:    my $uhome=&homeserver($uname,$udomain);
                   3957:    if ($regexp) {
                   3958:        $regexp=&escape($regexp);
                   3959:    } else {
                   3960:        $regexp='.';
                   3961:    }
                   3962:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3963:    my @pairs=split(/\&/,$rep);
                   3964:    my %returnhash=();
                   3965:    foreach my $item (@pairs) {
                   3966:        my ($key,$value)=split(/=/,$item,2);
                   3967:        next if ($key =~ /^error: 2 /);
                   3968:        $returnhash{$key}=&thaw_unescape($value);
                   3969:    }
                   3970:    return %returnhash;
1.717     albertel 3971: }
                   3972: 
1.407     www      3973: # -------------------------------------------------------------- keys interface
                   3974: 
                   3975: sub getkeys {
                   3976:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3977:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3978:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3979:    my $uhome=&homeserver($uname,$udomain);
                   3980:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3981:    my @keyarray=();
1.800     albertel 3982:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3983:       next if ($key =~ /^error: 2 /);
1.800     albertel 3984:       push(@keyarray,&unescape($key));
1.407     www      3985:    }
                   3986:    return @keyarray;
1.318     matthew  3987: }
                   3988: 
1.319     matthew  3989: # --------------------------------------------------------------- currentdump
                   3990: sub currentdump {
1.328     matthew  3991:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3992:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3993:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3994:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3995:    my $uhome = &homeserver($sname,$sdom);
                   3996:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3997:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3998:    #
1.318     matthew  3999:    my %returnhash=();
1.319     matthew  4000:    #
                   4001:    if ($rep eq "unknown_cmd") { 
                   4002:        # an old lond will not know currentdump
                   4003:        # Do a dump and make it look like a currentdump
1.822     albertel 4004:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4005:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4006:        my %hash = @tmp;
                   4007:        @tmp=();
1.424     matthew  4008:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4009:    } else {
                   4010:        my @pairs=split(/\&/,$rep);
1.800     albertel 4011:        foreach my $pair (@pairs) {
                   4012:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4013:            my ($symb,$param) = split(/:/,$key);
                   4014:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4015:                                                         &thaw_unescape($value);
1.319     matthew  4016:        }
1.191     harris41 4017:    }
1.12      www      4018:    return %returnhash;
1.424     matthew  4019: }
                   4020: 
                   4021: sub convert_dump_to_currentdump{
                   4022:     my %hash = %{shift()};
                   4023:     my %returnhash;
                   4024:     # Code ripped from lond, essentially.  The only difference
                   4025:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4026:     # we might run in to problems with parameter names =~ /^v\./
                   4027:     while (my ($key,$value) = each(%hash)) {
                   4028:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4029: 	$symb  = &unescape($symb);
                   4030: 	$param = &unescape($param);
1.424     matthew  4031:         next if ($v eq 'version' || $symb eq 'keys');
                   4032:         next if (exists($returnhash{$symb}) &&
                   4033:                  exists($returnhash{$symb}->{$param}) &&
                   4034:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4035:         $returnhash{$symb}->{$param}=$value;
                   4036:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4037:     }
                   4038:     #
                   4039:     # Remove all of the keys in the hashes which keep track of
                   4040:     # the version of the parameter.
                   4041:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4042:         # use a foreach because we are going to delete from the hash.
                   4043:         foreach my $key (keys(%$param_hash)) {
                   4044:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4045:         }
                   4046:     }
                   4047:     return \%returnhash;
1.12      www      4048: }
                   4049: 
1.627     albertel 4050: # ------------------------------------------------------ critical inc interface
                   4051: 
                   4052: sub cinc {
                   4053:     return &inc(@_,'critical');
                   4054: }
                   4055: 
1.449     matthew  4056: # --------------------------------------------------------------- inc interface
                   4057: 
                   4058: sub inc {
1.627     albertel 4059:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4060:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4061:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4062:     my $uhome=&homeserver($uname,$udomain);
                   4063:     my $items='';
                   4064:     if (! ref($store)) {
                   4065:         # got a single value, so use that instead
                   4066:         $items = &escape($store).'=&';
                   4067:     } elsif (ref($store) eq 'SCALAR') {
                   4068:         $items = &escape($$store).'=&';        
                   4069:     } elsif (ref($store) eq 'ARRAY') {
                   4070:         $items = join('=&',map {&escape($_);} @{$store});
                   4071:     } elsif (ref($store) eq 'HASH') {
                   4072:         while (my($key,$value) = each(%{$store})) {
                   4073:             $items.= &escape($key).'='.&escape($value).'&';
                   4074:         }
                   4075:     }
                   4076:     $items=~s/\&$//;
1.627     albertel 4077:     if ($critical) {
                   4078: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4079:     } else {
                   4080: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4081:     }
1.449     matthew  4082: }
                   4083: 
1.12      www      4084: # --------------------------------------------------------------- put interface
                   4085: 
                   4086: sub put {
1.134     albertel 4087:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4088:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4089:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4090:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4091:    my $items='';
1.800     albertel 4092:    foreach my $item (keys(%$storehash)) {
                   4093:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4094:    }
1.12      www      4095:    $items=~s/\&$//;
1.134     albertel 4096:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4097: }
                   4098: 
1.631     albertel 4099: # ------------------------------------------------------------ newput interface
                   4100: 
                   4101: sub newput {
                   4102:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4104:    if (!$uname) { $uname=$env{'user.name'}; }
                   4105:    my $uhome=&homeserver($uname,$udomain);
                   4106:    my $items='';
                   4107:    foreach my $key (keys(%$storehash)) {
                   4108:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4109:    }
                   4110:    $items=~s/\&$//;
                   4111:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4112: }
                   4113: 
                   4114: # ---------------------------------------------------------  putstore interface
                   4115: 
1.524     raeburn  4116: sub putstore {
1.715     albertel 4117:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4119:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4120:    my $uhome=&homeserver($uname,$udomain);
                   4121:    my $items='';
1.715     albertel 4122:    foreach my $key (keys(%$storehash)) {
                   4123:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4124:    }
1.715     albertel 4125:    $items=~s/\&$//;
1.716     albertel 4126:    my $esc_symb=&escape($symb);
                   4127:    my $esc_v=&escape($version);
1.715     albertel 4128:    my $reply =
1.716     albertel 4129:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4130: 	      $uhome);
                   4131:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4132:        # gfall back to way things use to be done
1.715     albertel 4133:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4134: 			    $uname);
1.524     raeburn  4135:    }
1.715     albertel 4136:    return $reply;
                   4137: }
                   4138: 
                   4139: sub old_putstore {
1.716     albertel 4140:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4142:     if (!$uname) { $uname=$env{'user.name'}; }
                   4143:     my $uhome=&homeserver($uname,$udomain);
                   4144:     my %newstorehash;
1.800     albertel 4145:     foreach my $item (keys(%$storehash)) {
                   4146: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4147: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4148:     }
                   4149:     my $items='';
                   4150:     my %allitems = ();
1.800     albertel 4151:     foreach my $item (keys(%newstorehash)) {
                   4152: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4153: 	    my $key = $1.':keys:'.$2;
                   4154: 	    $allitems{$key} .= $3.':';
                   4155: 	}
1.800     albertel 4156: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4157:     }
1.800     albertel 4158:     foreach my $item (keys(%allitems)) {
                   4159: 	$allitems{$item} =~ s/\:$//;
                   4160: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4161:     }
                   4162:     $items=~s/\&$//;
                   4163:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4164: }
                   4165: 
1.47      www      4166: # ------------------------------------------------------ critical put interface
                   4167: 
                   4168: sub cput {
1.134     albertel 4169:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4170:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4171:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4172:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4173:    my $items='';
1.800     albertel 4174:    foreach my $item (keys(%$storehash)) {
                   4175:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4176:    }
1.47      www      4177:    $items=~s/\&$//;
1.134     albertel 4178:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4179: }
                   4180: 
                   4181: # -------------------------------------------------------------- eget interface
                   4182: 
                   4183: sub eget {
1.133     albertel 4184:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4185:    my $items='';
1.800     albertel 4186:    foreach my $item (@$storearr) {
                   4187:        $items.=&escape($item).'&';
1.191     harris41 4188:    }
1.12      www      4189:    $items=~s/\&$//;
1.620     albertel 4190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4191:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4192:    my $uhome=&homeserver($uname,$udomain);
                   4193:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4194:    my @pairs=split(/\&/,$rep);
                   4195:    my %returnhash=();
1.42      www      4196:    my $i=0;
1.800     albertel 4197:    foreach my $item (@$storearr) {
                   4198:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4199:       $i++;
1.191     harris41 4200:    }
1.12      www      4201:    return %returnhash;
                   4202: }
                   4203: 
1.667     albertel 4204: # ------------------------------------------------------------ tmpput interface
                   4205: sub tmpput {
1.802     raeburn  4206:     my ($storehash,$server,$context)=@_;
1.667     albertel 4207:     my $items='';
1.800     albertel 4208:     foreach my $item (keys(%$storehash)) {
                   4209: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4210:     }
                   4211:     $items=~s/\&$//;
1.802     raeburn  4212:     if (defined($context)) {
                   4213:         $items .= ':'.&escape($context);
                   4214:     }
1.667     albertel 4215:     return &reply("tmpput:$items",$server);
                   4216: }
                   4217: 
                   4218: # ------------------------------------------------------------ tmpget interface
                   4219: sub tmpget {
1.688     albertel 4220:     my ($token,$server)=@_;
                   4221:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4222:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4223:     my %returnhash;
                   4224:     foreach my $item (split(/\&/,$rep)) {
                   4225: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4226:         next if ($key =~ /^error: 2 /);
1.667     albertel 4227: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4228:     }
                   4229:     return %returnhash;
                   4230: }
                   4231: 
1.688     albertel 4232: # ------------------------------------------------------------ tmpget interface
                   4233: sub tmpdel {
                   4234:     my ($token,$server)=@_;
                   4235:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4236:     return &reply("tmpdel:$token",$server);
                   4237: }
                   4238: 
1.765     albertel 4239: # -------------------------------------------------- portfolio access checking
                   4240: 
                   4241: sub portfolio_access {
1.766     albertel 4242:     my ($requrl) = @_;
1.765     albertel 4243:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4244:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4245:     if ($result) {
                   4246:         my %setters;
                   4247:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4248:             my ($startblock,$endblock) =
                   4249:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4250:             if ($startblock && $endblock) {
                   4251:                 return 'B';
                   4252:             }
                   4253:         } else {
                   4254:             my ($startblock,$endblock) =
                   4255:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4256:             if ($startblock && $endblock) {
                   4257:                 return 'B';
                   4258:             }
                   4259:         }
                   4260:     }
1.765     albertel 4261:     if ($result eq 'ok') {
1.766     albertel 4262:        return 'F';
1.765     albertel 4263:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4264:        return 'A';
1.765     albertel 4265:     }
1.766     albertel 4266:     return '';
1.765     albertel 4267: }
                   4268: 
                   4269: sub get_portfolio_access {
1.767     albertel 4270:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4271: 
                   4272:     if (!ref($access_hash)) {
                   4273: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4274: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4275: 						   $file_name);
                   4276: 	$access_hash = $access_controls{$file_name};
                   4277:     }
                   4278: 
1.765     albertel 4279:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4280:     my $now = time;
                   4281:     if (ref($access_hash) eq 'HASH') {
                   4282:         foreach my $key (keys(%{$access_hash})) {
                   4283:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4284:             if ($start > $now) {
                   4285:                 next;
                   4286:             }
                   4287:             if ($end && $end<$now) {
                   4288:                 next;
                   4289:             }
                   4290:             if ($scope eq 'public') {
                   4291:                 $public = $key;
                   4292:                 last;
                   4293:             } elsif ($scope eq 'guest') {
                   4294:                 $guest = $key;
                   4295:             } elsif ($scope eq 'domains') {
                   4296:                 push(@domains,$key);
                   4297:             } elsif ($scope eq 'users') {
                   4298:                 push(@users,$key);
                   4299:             } elsif ($scope eq 'course') {
                   4300:                 push(@courses,$key);
                   4301:             } elsif ($scope eq 'group') {
                   4302:                 push(@groups,$key);
                   4303:             }
                   4304:         }
                   4305:         if ($public) {
                   4306:             return 'ok';
                   4307:         }
                   4308:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4309:             if ($guest) {
                   4310:                 return $guest;
                   4311:             }
                   4312:         } else {
                   4313:             if (@domains > 0) {
                   4314:                 foreach my $domkey (@domains) {
                   4315:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4316:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4317:                             return 'ok';
                   4318:                         }
                   4319:                     }
                   4320:                 }
                   4321:             }
                   4322:             if (@users > 0) {
                   4323:                 foreach my $userkey (@users) {
1.865     raeburn  4324:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4325:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4326:                             if (ref($item) eq 'HASH') {
                   4327:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4328:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4329:                                     return 'ok';
                   4330:                                 }
                   4331:                             }
                   4332:                         }
                   4333:                     } 
1.765     albertel 4334:                 }
                   4335:             }
                   4336:             my %roleshash;
                   4337:             my @courses_and_groups = @courses;
                   4338:             push(@courses_and_groups,@groups); 
                   4339:             if (@courses_and_groups > 0) {
                   4340:                 my (%allgroups,%allroles); 
                   4341:                 my ($start,$end,$role,$sec,$group);
                   4342:                 foreach my $envkey (%env) {
1.811     albertel 4343:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4344:                         my $cid = $2.'_'.$3; 
                   4345:                         if ($1 eq 'gr') {
                   4346:                             $group = $4;
                   4347:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4348:                         } else {
                   4349:                             if ($4 eq '') {
                   4350:                                 $sec = 'none';
                   4351:                             } else {
                   4352:                                 $sec = $4;
                   4353:                             }
                   4354:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4355:                         }
1.811     albertel 4356:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4357:                         my $cid = $2.'_'.$3;
                   4358:                         if ($4 eq '') {
                   4359:                             $sec = 'none';
                   4360:                         } else {
                   4361:                             $sec = $4;
                   4362:                         }
                   4363:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4364:                     }
                   4365:                 }
                   4366:                 if (keys(%allroles) == 0) {
                   4367:                     return;
                   4368:                 }
                   4369:                 foreach my $key (@courses_and_groups) {
                   4370:                     my %content = %{$$access_hash{$key}};
                   4371:                     my $cnum = $content{'number'};
                   4372:                     my $cdom = $content{'domain'};
                   4373:                     my $cid = $cdom.'_'.$cnum;
                   4374:                     if (!exists($allroles{$cid})) {
                   4375:                         next;
                   4376:                     }    
                   4377:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4378:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4379:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4380:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4381:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4382:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4383:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4384:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4385:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4386:                                         if (grep/^all$/,@sections) {
                   4387:                                             return 'ok';
                   4388:                                         } else {
                   4389:                                             if (grep/^$sec$/,@sections) {
                   4390:                                                 return 'ok';
                   4391:                                             }
                   4392:                                         }
                   4393:                                     }
                   4394:                                 }
                   4395:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4396:                                     if (grep/^none$/,@groups) {
                   4397:                                         return 'ok';
                   4398:                                     }
                   4399:                                 } else {
                   4400:                                     if (grep/^all$/,@groups) {
                   4401:                                         return 'ok';
                   4402:                                     } 
                   4403:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4404:                                         if (grep/^$group$/,@groups) {
                   4405:                                             return 'ok';
                   4406:                                         }
                   4407:                                     }
                   4408:                                 } 
                   4409:                             }
                   4410:                         }
                   4411:                     }
                   4412:                 }
                   4413:             }
                   4414:             if ($guest) {
                   4415:                 return $guest;
                   4416:             }
                   4417:         }
                   4418:     }
                   4419:     return;
                   4420: }
                   4421: 
                   4422: sub course_group_datechecker {
                   4423:     my ($dates,$now,$status) = @_;
                   4424:     my ($start,$end) = split(/\./,$dates);
                   4425:     if (!$start && !$end) {
                   4426:         return 'ok';
                   4427:     }
                   4428:     if (grep/^active$/,@{$status}) {
                   4429:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4430:             return 'ok';
                   4431:         }
                   4432:     }
                   4433:     if (grep/^previous$/,@{$status}) {
                   4434:         if ($end > $now ) {
                   4435:             return 'ok';
                   4436:         }
                   4437:     }
                   4438:     if (grep/^future$/,@{$status}) {
                   4439:         if ($start > $now) {
                   4440:             return 'ok';
                   4441:         }
                   4442:     }
                   4443:     return; 
                   4444: }
                   4445: 
                   4446: sub parse_portfolio_url {
                   4447:     my ($url) = @_;
                   4448: 
                   4449:     my ($type,$udom,$unum,$group,$file_name);
                   4450:     
1.823     albertel 4451:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4452: 	$type = 1;
                   4453:         $udom = $1;
                   4454:         $unum = $2;
                   4455:         $file_name = $3;
1.823     albertel 4456:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4457: 	$type = 2;
                   4458:         $udom = $1;
                   4459:         $unum = $2;
                   4460:         $group = $3;
                   4461:         $file_name = $3.'/'.$4;
                   4462:     }
                   4463:     if (wantarray) {
                   4464: 	return ($type,$udom,$unum,$file_name,$group);
                   4465:     }
                   4466:     return $type;
                   4467: }
                   4468: 
                   4469: sub is_portfolio_url {
                   4470:     my ($url) = @_;
                   4471:     return scalar(&parse_portfolio_url($url));
                   4472: }
                   4473: 
1.798     raeburn  4474: sub is_portfolio_file {
                   4475:     my ($file) = @_;
1.820     raeburn  4476:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4477:         return 1;
                   4478:     }
                   4479:     return;
                   4480: }
                   4481: 
1.976     raeburn  4482: sub usertools_access {
1.985     raeburn  4483:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4484:     my ($access,%tools);
                   4485:     if ($context eq '') {
                   4486:         $context = 'tools';
                   4487:     }
                   4488:     if ($context eq 'requestcourses') {
                   4489:         %tools = (
                   4490:                       official   => 1,
                   4491:                       unofficial => 1,
                   4492:                  );
                   4493:     } else {
                   4494:         %tools = (
                   4495:                       aboutme   => 1,
                   4496:                       blog      => 1,
                   4497:                       portfolio => 1,
                   4498:                  );
                   4499:     }
1.976     raeburn  4500:     return if (!defined($tools{$tool}));
                   4501: 
                   4502:     if ((!defined($udom)) || (!defined($uname))) {
                   4503:         $udom = $env{'user.domain'};
                   4504:         $uname = $env{'user.name'};
                   4505:     }
                   4506: 
1.978     raeburn  4507:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4508:         if ($action ne 'reload') {
1.985     raeburn  4509:             if ($context eq 'requestcourses') {
                   4510:                 return $env{'environment.canrequest.'.$tool};
                   4511:             } else {
                   4512:                 return $env{'environment.availabletools.'.$tool};
                   4513:             }
                   4514:         }
1.976     raeburn  4515:     }
                   4516: 
                   4517:     my ($toolstatus,$inststatus);
                   4518: 
1.985     raeburn  4519:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4520:          ($action ne 'reload')) {
                   4521:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4522:         $inststatus = $env{'environment.inststatus'};
                   4523:     } else {
1.985     raeburn  4524:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
                   4525:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4526:         $inststatus = $userenv{'inststatus'};
                   4527:     }
                   4528: 
                   4529:     if ($toolstatus ne '') {
                   4530:         if ($toolstatus) {
                   4531:             $access = 1;
                   4532:         } else {
                   4533:             $access = 0;
                   4534:         }
                   4535:         return $access;
                   4536:     }
                   4537: 
                   4538:     my $is_adv = &is_advanced_user($udom,$uname);
                   4539:     my %domdef = &get_domain_defaults($udom);
                   4540:     if (ref($domdef{$tool}) eq 'HASH') {
                   4541:         if ($is_adv) {
                   4542:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4543:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4544:                     $access = 1;
                   4545:                 } else {
                   4546:                     $access = 0;
                   4547:                 }
                   4548:                 return $access;
                   4549:             }
                   4550:         }
                   4551:         if ($inststatus ne '') {
                   4552:             my ($hasaccess,$hasnoaccess);
                   4553:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4554:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4555:                     if ($domdef{$tool}{$affiliation}) {
                   4556:                         $hasaccess = 1;
                   4557:                     } else {
                   4558:                         $hasnoaccess = 1;
                   4559:                     }
                   4560:                 }
                   4561:             }
                   4562:             if ($hasaccess || $hasnoaccess) {
                   4563:                 if ($hasaccess) {
                   4564:                     $access = 1;
                   4565:                 } elsif ($hasnoaccess) {
                   4566:                     $access = 0; 
                   4567:                 }
                   4568:                 return $access;
                   4569:             }
                   4570:         } else {
                   4571:             if ($domdef{$tool}{'default'} ne '') {
                   4572:                 if ($domdef{$tool}{'default'}) {
                   4573:                     $access = 1;
                   4574:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4575:                     $access = 0;
                   4576:                 }
                   4577:                 return $access;
                   4578:             }
                   4579:         }
                   4580:     } else {
1.985     raeburn  4581:         if ($context eq 'tools') {
                   4582:             $access = 1;
                   4583:         } else {
                   4584:             $access = 0;
                   4585:         }
1.976     raeburn  4586:         return $access;
                   4587:     }
                   4588: }
                   4589: 
                   4590: sub is_advanced_user {
                   4591:     my ($udom,$uname) = @_;
                   4592:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4593:     my %allroles;
                   4594:     my $is_adv;
                   4595:     foreach my $role (keys(%roleshash)) {
                   4596:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4597:         my $area = '/'.$tdomain.'/'.$trest;
                   4598:         if ($sec ne '') {
                   4599:             $area .= '/'.$sec;
                   4600:         }
                   4601:         if (($area ne '') && ($trole ne '')) {
                   4602:             my $spec=$trole.'.'.$area;
                   4603:             if ($trole =~ /^cr\//) {
                   4604:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4605:             } elsif ($trole ne 'gr') {
                   4606:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4607:             }
                   4608:         }
                   4609:     }
                   4610:     foreach my $role (keys(%allroles)) {
                   4611:         last if ($is_adv);
                   4612:         foreach my $item (split(/:/,$allroles{$role})) {
                   4613:             if ($item ne '') {
                   4614:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4615:                 if ($privilege eq 'adv') {
                   4616:                     $is_adv = 1;
                   4617:                     last;
                   4618:                 }
                   4619:             }
                   4620:         }
                   4621:     }
                   4622:     return $is_adv;
                   4623: }
1.798     raeburn  4624: 
1.341     www      4625: # ---------------------------------------------- Custom access rule evaluation
                   4626: 
                   4627: sub customaccess {
                   4628:     my ($priv,$uri)=@_;
1.807     albertel 4629:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4630:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4631:     $udom = &LONCAPA::clean_domain($udom);
                   4632:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4633:     my $access=0;
1.800     albertel 4634:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4635: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4636: 	if ($type eq 'user') {
                   4637: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4638: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4639: 		if ($tdom) {
                   4640: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4641: 		}
1.896     albertel 4642: 		if ($tuname) {
                   4643: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4644: 		}
                   4645: 		$access=($effect eq 'allow');
                   4646: 		last;
                   4647: 	    }
                   4648: 	} else {
                   4649: 	    if ($role) {
                   4650: 		if ($role ne $urole) { next; }
                   4651: 	    }
                   4652: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4653: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4654: 		if ($tdom) {
                   4655: 		    if ($tdom ne $udom) { next; }
                   4656: 		}
                   4657: 		if ($tcrs) {
                   4658: 		    if ($tcrs ne $ucrs) { next; }
                   4659: 		}
                   4660: 		if ($tsec) {
                   4661: 		    if ($tsec ne $usec) { next; }
                   4662: 		}
                   4663: 		$access=($effect eq 'allow');
                   4664: 		last;
                   4665: 	    }
                   4666: 	    if ($realm eq '' && $role eq '') {
                   4667: 		$access=($effect eq 'allow');
                   4668: 	    }
1.402     bowersj2 4669: 	}
1.341     www      4670:     }
                   4671:     return $access;
                   4672: }
                   4673: 
1.103     harris41 4674: # ------------------------------------------------- Check for a user privilege
1.12      www      4675: 
                   4676: sub allowed {
1.810     raeburn  4677:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4678:     my $ver_orguri=$uri;
1.439     www      4679:     $uri=&deversion($uri);
1.152     www      4680:     my $orguri=$uri;
1.52      www      4681:     $uri=&declutter($uri);
1.809     raeburn  4682: 
1.810     raeburn  4683:     if ($priv eq 'evb') {
                   4684: # Evade communication block restrictions for specified role in a course
                   4685:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4686:             return $1;
                   4687:         } else {
                   4688:             return;
                   4689:         }
                   4690:     }
                   4691: 
1.620     albertel 4692:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4693: # Free bre access to adm and meta resources
1.775     albertel 4694:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4695: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4696: 	&& ($priv eq 'bre')) {
1.14      www      4697: 	return 'F';
1.159     www      4698:     }
                   4699: 
1.545     banghart 4700: # Free bre access to user's own portfolio contents
1.714     raeburn  4701:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4702:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4703: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4704:         my %setters;
                   4705:         my ($startblock,$endblock) = 
                   4706:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4707:         if ($startblock && $endblock) {
                   4708:             return 'B';
                   4709:         } else {
                   4710:             return 'F';
                   4711:         }
1.545     banghart 4712:     }
                   4713: 
1.762     raeburn  4714: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4715:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4716:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4717:         if (exists($env{'request.course.id'})) {
                   4718:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4719:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4720:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4721:                 my $courseprivid=$env{'request.course.id'};
                   4722:                 $courseprivid=~s/\_/\//;
                   4723:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4724:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4725:                     return $1; 
1.762     raeburn  4726:                 } else {
                   4727:                     if ($env{'request.course.sec'}) {
                   4728:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4729:                     }
                   4730:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4731:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4732:                         return $2;
                   4733:                     }
1.714     raeburn  4734:                 }
                   4735:             }
                   4736:         }
                   4737:     }
                   4738: 
1.159     www      4739: # Free bre to public access
                   4740: 
                   4741:     if ($priv eq 'bre') {
1.238     www      4742:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4743: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4744:            return 'F'; 
                   4745:         }
1.238     www      4746:         if ($copyright eq 'priv') {
                   4747:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4748: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4749: 		return '';
                   4750:             }
                   4751:         }
                   4752:         if ($copyright eq 'domain') {
                   4753:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4754: 	    unless (($env{'user.domain'} eq $1) ||
                   4755:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4756: 		return '';
                   4757:             }
1.262     matthew  4758:         }
1.620     albertel 4759:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4760:             # Library role, so allow browsing of resources in this domain.
                   4761:             return 'F';
1.238     www      4762:         }
1.341     www      4763:         if ($copyright eq 'custom') {
                   4764: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4765:         }
1.14      www      4766:     }
1.264     matthew  4767:     # Domain coordinator is trying to create a course
1.620     albertel 4768:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4769:         # uri is the requested domain in this case.
                   4770:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4771:         # a role of dc for the domain in question.
1.620     albertel 4772:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4773:     }
1.29      www      4774: 
1.52      www      4775:     my $thisallowed='';
                   4776:     my $statecond=0;
                   4777:     my $courseprivid='';
                   4778: 
                   4779: # Course
                   4780: 
1.620     albertel 4781:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4782:        $thisallowed.=$1;
                   4783:     }
1.29      www      4784: 
1.52      www      4785: # Domain
                   4786: 
1.620     albertel 4787:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4788:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4789:        $thisallowed.=$1;
                   4790:     }
1.52      www      4791: 
                   4792: # Course: uri itself is a course
1.66      www      4793:     my $courseuri=$uri;
                   4794:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4795:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4796: 
1.620     albertel 4797:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4798:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4799:        $thisallowed.=$1;
                   4800:     }
1.29      www      4801: 
1.665     albertel 4802: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4803: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4804:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4805: 	$thisallowed='';
1.671     raeburn  4806:         my ($match)=&is_on_map($uri);
                   4807:         if ($match) {
                   4808:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4809:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4810:                 $thisallowed.=$1;
                   4811:             }
                   4812:         } else {
1.705     albertel 4813:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4814:             if ($refuri) {
                   4815:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4816:                     $thisallowed='F';
1.671     raeburn  4817:                 } else {
                   4818:                     $refuri=&declutter($refuri);
                   4819:                     my ($match) = &is_on_map($refuri);
                   4820:                     if ($match) {
                   4821:                         $thisallowed='F';
                   4822:                     }
1.669     raeburn  4823:                 }
1.671     raeburn  4824:             }
                   4825:         }
1.314     www      4826:     }
1.492     albertel 4827: 
1.766     albertel 4828:     if ($priv eq 'bre'
                   4829: 	&& $thisallowed ne 'F' 
                   4830: 	&& $thisallowed ne '2'
                   4831: 	&& &is_portfolio_url($uri)) {
                   4832: 	$thisallowed = &portfolio_access($uri);
                   4833:     }
                   4834:     
1.52      www      4835: # Full access at system, domain or course-wide level? Exit.
1.29      www      4836:     if ($thisallowed=~/F/) {
                   4837: 	return 'F';
                   4838:     }
                   4839: 
1.52      www      4840: # If this is generating or modifying users, exit with special codes
1.29      www      4841: 
1.643     www      4842:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4843: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4844: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4845: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4846: 	    unless ($auname) { return $thisallowed; }
                   4847: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4848: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4849: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4850: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4851: 	}
1.52      www      4852: 	return $thisallowed;
                   4853:     }
                   4854: #
1.103     harris41 4855: # Gathered so far: system, domain and course wide privileges
1.52      www      4856: #
                   4857: # Course: See if uri or referer is an individual resource that is part of 
                   4858: # the course
                   4859: 
1.620     albertel 4860:     if ($env{'request.course.id'}) {
1.232     www      4861: 
1.620     albertel 4862:        $courseprivid=$env{'request.course.id'};
                   4863:        if ($env{'request.course.sec'}) {
                   4864:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4865:        }
                   4866:        $courseprivid=~s/\_/\//;
                   4867:        my $checkreferer=1;
1.232     www      4868:        my ($match,$cond)=&is_on_map($uri);
                   4869:        if ($match) {
                   4870:            $statecond=$cond;
1.620     albertel 4871:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4872:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4873:                $thisallowed.=$1;
                   4874:                $checkreferer=0;
                   4875:            }
1.29      www      4876:        }
1.83      www      4877:        
1.148     www      4878:        if ($checkreferer) {
1.620     albertel 4879: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4880:             unless ($refuri) {
1.800     albertel 4881:                 foreach my $key (keys(%env)) {
                   4882: 		    if ($key=~/^httpref\..*\*/) {
                   4883: 			my $pattern=$key;
1.156     www      4884:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4885:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4886:                         $pattern=~s/\//\\\//g;
1.152     www      4887:                         if ($orguri=~/$pattern/) {
1.800     albertel 4888: 			    $refuri=$env{$key};
1.148     www      4889:                         }
                   4890:                     }
1.191     harris41 4891:                 }
1.148     www      4892:             }
1.232     www      4893: 
1.148     www      4894:          if ($refuri) { 
1.152     www      4895: 	  $refuri=&declutter($refuri);
1.232     www      4896:           my ($match,$cond)=&is_on_map($refuri);
                   4897:             if ($match) {
                   4898:               my $refstatecond=$cond;
1.620     albertel 4899:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4900:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4901:                   $thisallowed.=$1;
1.53      www      4902:                   $uri=$refuri;
                   4903:                   $statecond=$refstatecond;
1.52      www      4904:               }
                   4905:           }
1.148     www      4906:         }
1.29      www      4907:        }
1.52      www      4908:    }
1.29      www      4909: 
1.52      www      4910: #
1.103     harris41 4911: # Gathered now: all privileges that could apply, and condition number
1.52      www      4912: # 
                   4913: #
                   4914: # Full or no access?
                   4915: #
1.29      www      4916: 
1.52      www      4917:     if ($thisallowed=~/F/) {
                   4918: 	return 'F';
                   4919:     }
1.29      www      4920: 
1.52      www      4921:     unless ($thisallowed) {
                   4922:         return '';
                   4923:     }
1.29      www      4924: 
1.52      www      4925: # Restrictions exist, deal with them
                   4926: #
                   4927: #   C:according to course preferences
                   4928: #   R:according to resource settings
                   4929: #   L:unless locked
                   4930: #   X:according to user session state
                   4931: #
                   4932: 
                   4933: # Possibly locked functionality, check all courses
1.54      www      4934: # Locks might take effect only after 10 minutes cache expiration for other
                   4935: # courses, and 2 minutes for current course
1.52      www      4936: 
                   4937:     my $envkey;
                   4938:     if ($thisallowed=~/L/) {
1.620     albertel 4939:         foreach $envkey (keys %env) {
1.54      www      4940:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4941:                my $courseid=$2;
                   4942:                my $roleid=$1.'.'.$2;
1.92      www      4943:                $courseid=~s/^\///;
1.54      www      4944:                my $expiretime=600;
1.620     albertel 4945:                if ($env{'request.role'} eq $roleid) {
1.54      www      4946: 		  $expiretime=120;
                   4947:                }
                   4948: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4949:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4950:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4951: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4952:                }
1.620     albertel 4953:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4954:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4955: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4956:                        &log($env{'user.domain'},$env{'user.name'},
                   4957:                             $env{'user.home'},
1.57      www      4958:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4959:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4960:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4961: 		       return '';
                   4962:                    }
                   4963:                }
1.620     albertel 4964:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4965:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4966: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4967:                        &log($env{'user.domain'},$env{'user.name'},
                   4968:                             $env{'user.home'},
1.57      www      4969:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4970:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4971:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4972: 		       return '';
                   4973:                    }
                   4974:                }
                   4975: 	   }
1.29      www      4976:        }
1.52      www      4977:     }
                   4978:    
                   4979: #
                   4980: # Rest of the restrictions depend on selected course
                   4981: #
                   4982: 
1.620     albertel 4983:     unless ($env{'request.course.id'}) {
1.766     albertel 4984: 	if ($thisallowed eq 'A') {
                   4985: 	    return 'A';
1.814     raeburn  4986:         } elsif ($thisallowed eq 'B') {
                   4987:             return 'B';
1.766     albertel 4988: 	} else {
                   4989: 	    return '1';
                   4990: 	}
1.52      www      4991:     }
1.29      www      4992: 
1.52      www      4993: #
                   4994: # Now user is definitely in a course
                   4995: #
1.53      www      4996: 
                   4997: 
                   4998: # Course preferences
                   4999: 
                   5000:    if ($thisallowed=~/C/) {
1.620     albertel 5001:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5002:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5003:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5004: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5005: 	   if ($priv ne 'pch') { 
                   5006: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5007: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5008: 			$env{'request.course.id'});
                   5009: 	   }
1.237     www      5010:            return '';
                   5011:        }
                   5012: 
1.620     albertel 5013:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5014: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5015: 	   if ($priv ne 'pch') { 
                   5016: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5017: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5018: 			$env{'request.course.id'});
                   5019: 	   }
1.54      www      5020:            return '';
                   5021:        }
1.53      www      5022:    }
                   5023: 
                   5024: # Resource preferences
                   5025: 
                   5026:    if ($thisallowed=~/R/) {
1.620     albertel 5027:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5028:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5029: 	   if ($priv ne 'pch') { 
                   5030: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5031: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5032: 	   }
                   5033: 	   return '';
1.54      www      5034:        }
1.53      www      5035:    }
1.30      www      5036: 
1.246     www      5037: # Restricted by state or randomout?
1.30      www      5038: 
1.52      www      5039:    if ($thisallowed=~/X/) {
1.620     albertel 5040:       if ($env{'acc.randomout'}) {
1.579     albertel 5041: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5042:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5043:             return ''; 
                   5044:          }
1.247     www      5045:       }
                   5046:       if (&condval($statecond)) {
1.52      www      5047: 	 return '2';
                   5048:       } else {
                   5049:          return '';
                   5050:       }
                   5051:    }
1.30      www      5052: 
1.766     albertel 5053:     if ($thisallowed eq 'A') {
                   5054: 	return 'A';
1.814     raeburn  5055:     } elsif ($thisallowed eq 'B') {
                   5056:         return 'B';
1.766     albertel 5057:     }
1.52      www      5058:    return 'F';
1.232     www      5059: }
                   5060: 
1.710     albertel 5061: sub split_uri_for_cond {
                   5062:     my $uri=&deversion(&declutter(shift));
                   5063:     my @uriparts=split(/\//,$uri);
                   5064:     my $filename=pop(@uriparts);
                   5065:     my $pathname=join('/',@uriparts);
                   5066:     return ($pathname,$filename);
                   5067: }
1.232     www      5068: # --------------------------------------------------- Is a resource on the map?
                   5069: 
                   5070: sub is_on_map {
1.710     albertel 5071:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5072:     #Trying to find the conditional for the file
1.620     albertel 5073:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5074: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5075:     if ($match) {
1.289     bowersj2 5076: 	return (1,$1);
                   5077:     } else {
1.434     www      5078: 	return (0,0);
1.289     bowersj2 5079:     }
1.12      www      5080: }
                   5081: 
1.427     www      5082: # --------------------------------------------------------- Get symb from alias
                   5083: 
                   5084: sub get_symb_from_alias {
                   5085:     my $symb=shift;
                   5086:     my ($map,$resid,$url)=&decode_symb($symb);
                   5087: # Already is a symb
                   5088:     if ($url) { return $symb; }
                   5089: # Must be an alias
                   5090:     my $aliassymb='';
                   5091:     my %bighash;
1.620     albertel 5092:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5093:                             &GDBM_READER(),0640)) {
                   5094:         my $rid=$bighash{'mapalias_'.$symb};
                   5095: 	if ($rid) {
                   5096: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5097: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5098: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5099: 	}
                   5100:         untie %bighash;
                   5101:     }
                   5102:     return $aliassymb;
                   5103: }
                   5104: 
1.12      www      5105: # ----------------------------------------------------------------- Define Role
                   5106: 
                   5107: sub definerole {
                   5108:   if (allowed('mcr','/')) {
                   5109:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5110:     foreach my $role (split(':',$sysrole)) {
                   5111: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5112:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5113:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5114: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5115:                return "refused:s:$crole&$cqual"; 
                   5116:             }
                   5117:         }
1.191     harris41 5118:     }
1.800     albertel 5119:     foreach my $role (split(':',$domrole)) {
                   5120: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5121:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5122:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5123: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5124:                return "refused:d:$crole&$cqual"; 
                   5125:             }
                   5126:         }
1.191     harris41 5127:     }
1.800     albertel 5128:     foreach my $role (split(':',$courole)) {
                   5129: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5130:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5131:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5132: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5133:                return "refused:c:$crole&$cqual"; 
                   5134:             }
                   5135:         }
1.191     harris41 5136:     }
1.620     albertel 5137:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5138:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5139: 	        "rolesdef_$rolename=".
                   5140:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5141:     return reply($command,$env{'user.home'});
1.12      www      5142:   } else {
                   5143:     return 'refused';
                   5144:   }
1.105     harris41 5145: }
                   5146: 
                   5147: # ---------------- Make a metadata query against the network of library servers
                   5148: 
                   5149: sub metadata_query {
1.244     matthew  5150:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5151:     my %rhash;
1.845     albertel 5152:     my %libserv = &all_library();
1.244     matthew  5153:     my @server_list = (defined($server_array) ? @$server_array
                   5154:                                               : keys(%libserv) );
                   5155:     for my $server (@server_list) {
1.118     harris41 5156: 	unless ($custom or $customshow) {
                   5157: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5158: 	    $rhash{$server}=$reply;
                   5159: 	}
                   5160: 	else {
                   5161: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5162: 			     &escape($custom).':'.&escape($customshow),
                   5163: 			     $server);
                   5164: 	    $rhash{$server}=$reply;
                   5165: 	}
1.112     harris41 5166:     }
1.118     harris41 5167:     return \%rhash;
1.240     www      5168: }
                   5169: 
                   5170: # ----------------------------------------- Send log queries and wait for reply
                   5171: 
                   5172: sub log_query {
                   5173:     my ($uname,$udom,$query,%filters)=@_;
                   5174:     my $uhome=&homeserver($uname,$udom);
                   5175:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5176:     my $uhost=&hostname($uhome);
1.800     albertel 5177:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5178:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5179:                        $uhome);
1.479     albertel 5180:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5181:     return get_query_reply($queryid);
                   5182: }
                   5183: 
1.818     raeburn  5184: # -------------------------- Update MySQL table for portfolio file
                   5185: 
                   5186: sub update_portfolio_table {
1.821     raeburn  5187:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5188:     if ($group ne '') {
                   5189:         $file_name =~s /^\Q$group\E//;
                   5190:     }
1.818     raeburn  5191:     my $homeserver = &homeserver($uname,$udom);
                   5192:     my $queryid=
1.821     raeburn  5193:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5194:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5195:     my $reply = &get_query_reply($queryid);
                   5196:     return $reply;
                   5197: }
                   5198: 
1.899     raeburn  5199: # -------------------------- Update MySQL allusers table
                   5200: 
                   5201: sub update_allusers_table {
                   5202:     my ($uname,$udom,$names) = @_;
                   5203:     my $homeserver = &homeserver($uname,$udom);
                   5204:     my $queryid=
                   5205:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5206:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5207:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5208:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5209:                'generation='.&escape($names->{'generation'}).'%%'.
                   5210:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5211:                'id='.&escape($names->{'id'}),$homeserver);
                   5212:     my $reply = &get_query_reply($queryid);
                   5213:     return $reply;
                   5214: }
                   5215: 
1.508     raeburn  5216: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5217: 
                   5218: sub fetch_enrollment_query {
1.511     raeburn  5219:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5220:     my $homeserver;
1.547     raeburn  5221:     my $maxtries = 1;
1.508     raeburn  5222:     if ($context eq 'automated') {
                   5223:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5224:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5225:     } else {
                   5226:         $homeserver = &homeserver($cnum,$dom);
                   5227:     }
1.838     albertel 5228:     my $host=&hostname($homeserver);
1.506     raeburn  5229:     my $cmd = '';
1.800     albertel 5230:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5231:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5232:     }
                   5233:     $cmd =~ s/%%$//;
                   5234:     $cmd = &escape($cmd);
                   5235:     my $query = 'fetchenrollment';
1.620     albertel 5236:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5237:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5238:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5239:         return 'error: '.$queryid;
                   5240:     }
1.506     raeburn  5241:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5242:     my $tries = 1;
                   5243:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5244:         $reply = &get_query_reply($queryid);
                   5245:         $tries ++;
                   5246:     }
1.526     raeburn  5247:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5248:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5249:     } else {
1.901     albertel 5250:         my @responses = split(/:/,$reply);
1.515     raeburn  5251:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5252:             foreach my $line (@responses) {
                   5253:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5254:                 $$replyref{$key} = $value;
                   5255:             }
                   5256:         } else {
1.506     raeburn  5257:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5258:             foreach my $line (@responses) {
                   5259:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5260:                 $$replyref{$key} = $value;
                   5261:                 if ($value > 0) {
1.800     albertel 5262:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5263:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5264:                         my $destname = $pathname.'/'.$filename;
                   5265:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5266:                         if ($xml_classlist =~ /^error/) {
                   5267:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5268:                         } else {
1.506     raeburn  5269:                             if ( open(FILE,">$destname") ) {
                   5270:                                 print FILE &unescape($xml_classlist);
                   5271:                                 close(FILE);
1.526     raeburn  5272:                             } else {
                   5273:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5274:                             }
                   5275:                         }
                   5276:                     }
                   5277:                 }
                   5278:             }
                   5279:         }
                   5280:         return 'ok';
                   5281:     }
                   5282:     return 'error';
                   5283: }
                   5284: 
1.242     www      5285: sub get_query_reply {
                   5286:     my $queryid=shift;
1.240     www      5287:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5288:     my $reply='';
                   5289:     for (1..100) {
                   5290: 	sleep 2;
                   5291:         if (-e $replyfile.'.end') {
1.448     albertel 5292: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5293: 		$reply = join('',<$fh>);
                   5294: 		close($fh);
1.240     www      5295: 	   } else { return 'error: reply_file_error'; }
1.242     www      5296:            return &unescape($reply);
                   5297: 	}
1.240     www      5298:     }
1.242     www      5299:     return 'timeout:'.$queryid;
1.240     www      5300: }
                   5301: 
                   5302: sub courselog_query {
1.241     www      5303: #
                   5304: # possible filters:
                   5305: # url: url or symb
                   5306: # username
                   5307: # domain
                   5308: # action: view, submit, grade
                   5309: # start: timestamp
                   5310: # end: timestamp
                   5311: #
1.240     www      5312:     my (%filters)=@_;
1.620     albertel 5313:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5314:     if ($filters{'url'}) {
                   5315: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5316:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5317:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5318:     }
1.620     albertel 5319:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5320:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5321:     return &log_query($cname,$cdom,'courselog',%filters);
                   5322: }
                   5323: 
                   5324: sub userlog_query {
1.858     raeburn  5325: #
                   5326: # possible filters:
                   5327: # action: log check role
                   5328: # start: timestamp
                   5329: # end: timestamp
                   5330: #
1.240     www      5331:     my ($uname,$udom,%filters)=@_;
                   5332:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5333: }
                   5334: 
1.506     raeburn  5335: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5336: 
                   5337: sub auto_run {
1.508     raeburn  5338:     my ($cnum,$cdom) = @_;
1.876     raeburn  5339:     my $response = 0;
                   5340:     my $settings;
                   5341:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5342:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5343:         $settings = $domconfig{'autoenroll'};
                   5344:         if ($settings->{'run'} eq '1') {
                   5345:             $response = 1;
                   5346:         }
                   5347:     } else {
1.934     raeburn  5348:         my $homeserver;
                   5349:         if (&is_course($cdom,$cnum)) {
                   5350:             $homeserver = &homeserver($cnum,$cdom);
                   5351:         } else {
                   5352:             $homeserver = &domain($cdom,'primary');
                   5353:         }
                   5354:         if ($homeserver ne 'no_host') {
                   5355:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5356:         }
1.876     raeburn  5357:     }
1.506     raeburn  5358:     return $response;
                   5359: }
1.776     albertel 5360: 
1.506     raeburn  5361: sub auto_get_sections {
1.508     raeburn  5362:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5363:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5364:     my @secs = ();
1.511     raeburn  5365:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5366:     unless ($response eq 'refused') {
1.901     albertel 5367:         @secs = split(/:/,$response);
1.506     raeburn  5368:     }
                   5369:     return @secs;
                   5370: }
1.776     albertel 5371: 
1.506     raeburn  5372: sub auto_new_course {
1.508     raeburn  5373:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5374:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5375:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5376:     return $response;
                   5377: }
1.776     albertel 5378: 
1.506     raeburn  5379: sub auto_validate_courseID {
1.508     raeburn  5380:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5381:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5382:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5383:     return $response;
                   5384: }
1.776     albertel 5385: 
1.506     raeburn  5386: sub auto_create_password {
1.873     raeburn  5387:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5388:     my ($homeserver,$response);
1.506     raeburn  5389:     my $create_passwd = 0;
                   5390:     my $authchk = '';
1.873     raeburn  5391:     if ($udom =~ /^$match_domain$/) {
                   5392:         $homeserver = &domain($udom,'primary');
                   5393:     }
                   5394:     if ($homeserver eq '') {
                   5395:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5396:             $homeserver = &homeserver($cnum,$cdom);
                   5397:         }
                   5398:     }
                   5399:     if ($homeserver eq '') {
                   5400:         $authchk = 'nodomain';
1.506     raeburn  5401:     } else {
1.873     raeburn  5402:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5403:         if ($response eq 'refused') {
                   5404:             $authchk = 'refused';
                   5405:         } else {
1.901     albertel 5406:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5407:         }
1.506     raeburn  5408:     }
                   5409:     return ($authparam,$create_passwd,$authchk);
                   5410: }
                   5411: 
1.706     raeburn  5412: sub auto_photo_permission {
                   5413:     my ($cnum,$cdom,$students) = @_;
                   5414:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5415:     my ($outcome,$perm_reqd,$conditions) = 
                   5416: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5417:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5418: 	return (undef,undef);
                   5419:     }
1.706     raeburn  5420:     return ($outcome,$perm_reqd,$conditions);
                   5421: }
                   5422: 
                   5423: sub auto_checkphotos {
                   5424:     my ($uname,$udom,$pid) = @_;
                   5425:     my $homeserver = &homeserver($uname,$udom);
                   5426:     my ($result,$resulttype);
                   5427:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5428: 				   &escape($uname).':'.&escape($pid),
                   5429: 				   $homeserver));
1.709     albertel 5430:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5431: 	return (undef,undef);
                   5432:     }
1.706     raeburn  5433:     if ($outcome) {
                   5434:         ($result,$resulttype) = split(/:/,$outcome);
                   5435:     } 
                   5436:     return ($result,$resulttype);
                   5437: }
                   5438: 
                   5439: sub auto_photochoice {
                   5440:     my ($cnum,$cdom) = @_;
                   5441:     my $homeserver = &homeserver($cnum,$cdom);
                   5442:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5443: 						       &escape($cdom),
                   5444: 						       $homeserver)));
1.709     albertel 5445:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5446: 	return (undef,undef);
                   5447:     }
1.706     raeburn  5448:     return ($update,$comment);
                   5449: }
                   5450: 
                   5451: sub auto_photoupdate {
                   5452:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5453:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5454:     my $host=&hostname($homeserver);
1.706     raeburn  5455:     my $cmd = '';
                   5456:     my $maxtries = 1;
1.800     albertel 5457:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5458:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5459:     }
                   5460:     $cmd =~ s/%%$//;
                   5461:     $cmd = &escape($cmd);
                   5462:     my $query = 'institutionalphotos';
                   5463:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5464:     unless ($queryid=~/^\Q$host\E\_/) {
                   5465:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5466:         return 'error: '.$queryid;
                   5467:     }
                   5468:     my $reply = &get_query_reply($queryid);
                   5469:     my $tries = 1;
                   5470:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5471:         $reply = &get_query_reply($queryid);
                   5472:         $tries ++;
                   5473:     }
                   5474:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5475:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5476:     } else {
                   5477:         my @responses = split(/:/,$reply);
                   5478:         my $outcome = shift(@responses); 
                   5479:         foreach my $item (@responses) {
                   5480:             my ($key,$value) = split(/=/,$item);
                   5481:             $$photo{$key} = $value;
                   5482:         }
                   5483:         return $outcome;
                   5484:     }
                   5485:     return 'error';
                   5486: }
                   5487: 
1.521     raeburn  5488: sub auto_instcode_format {
1.793     albertel 5489:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5490: 	$cat_order) = @_;
1.521     raeburn  5491:     my $courses = '';
1.772     raeburn  5492:     my @homeservers;
1.521     raeburn  5493:     if ($caller eq 'global') {
1.841     albertel 5494: 	my %servers = &get_servers($codedom,'library');
                   5495: 	foreach my $tryserver (keys(%servers)) {
                   5496: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5497: 		push(@homeservers,$tryserver);
                   5498: 	    }
1.584     raeburn  5499:         }
1.521     raeburn  5500:     } else {
1.772     raeburn  5501:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5502:     }
1.793     albertel 5503:     foreach my $code (keys(%{$instcodes})) {
                   5504:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5505:     }
                   5506:     chop($courses);
1.772     raeburn  5507:     my $ok_response = 0;
                   5508:     my $response;
                   5509:     while (@homeservers > 0 && $ok_response == 0) {
                   5510:         my $server = shift(@homeservers); 
                   5511:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5512:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5513:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5514: 		split(/:/,$response);
1.772     raeburn  5515:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5516:             push(@{$codetitles},&str2array($codetitles_str));
                   5517:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5518:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5519:             $ok_response = 1;
                   5520:         }
                   5521:     }
                   5522:     if ($ok_response) {
1.521     raeburn  5523:         return 'ok';
1.772     raeburn  5524:     } else {
                   5525:         return $response;
1.521     raeburn  5526:     }
                   5527: }
                   5528: 
1.792     raeburn  5529: sub auto_instcode_defaults {
                   5530:     my ($domain,$returnhash,$code_order) = @_;
                   5531:     my @homeservers;
1.841     albertel 5532: 
                   5533:     my %servers = &get_servers($domain,'library');
                   5534:     foreach my $tryserver (keys(%servers)) {
                   5535: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5536: 	    push(@homeservers,$tryserver);
                   5537: 	}
1.792     raeburn  5538:     }
1.841     albertel 5539: 
1.792     raeburn  5540:     my $response;
1.841     albertel 5541:     foreach my $server (@homeservers) {
1.792     raeburn  5542:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5543:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5544: 	
                   5545: 	foreach my $pair (split(/\&/,$response)) {
                   5546: 	    my ($name,$value)=split(/\=/,$pair);
                   5547: 	    if ($name eq 'code_order') {
                   5548: 		@{$code_order} = split(/\&/,&unescape($value));
                   5549: 	    } else {
                   5550: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5551: 	    }
                   5552: 	}
                   5553: 	return 'ok';
1.792     raeburn  5554:     }
1.841     albertel 5555: 
                   5556:     return $response;
1.792     raeburn  5557: } 
                   5558: 
1.777     albertel 5559: sub auto_validate_class_sec {
1.918     raeburn  5560:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5561:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5562:     my $ownerlist;
                   5563:     if (ref($owners) eq 'ARRAY') {
                   5564:         $ownerlist = join(',',@{$owners});
                   5565:     } else {
                   5566:         $ownerlist = $owners;
                   5567:     }
1.773     raeburn  5568:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5569:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5570:     return $response;
                   5571: }
                   5572: 
1.679     raeburn  5573: # ------------------------------------------------------- Course Group routines
                   5574: 
                   5575: sub get_coursegroups {
1.809     raeburn  5576:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5577:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5578: }
                   5579: 
1.679     raeburn  5580: sub modify_coursegroup {
                   5581:     my ($cdom,$cnum,$groupsettings) = @_;
                   5582:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5583: }
                   5584: 
1.809     raeburn  5585: sub toggle_coursegroup_status {
                   5586:     my ($cdom,$cnum,$group,$action) = @_;
                   5587:     my ($from_namespace,$to_namespace);
                   5588:     if ($action eq 'delete') {
                   5589:         $from_namespace = 'coursegroups';
                   5590:         $to_namespace = 'deleted_groups';
                   5591:     } else {
                   5592:         $from_namespace = 'deleted_groups';
                   5593:         $to_namespace = 'coursegroups';
                   5594:     }
                   5595:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5596:     if (my $tmp = &error(%curr_group)) {
                   5597:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5598:         return ('read error',$tmp);
                   5599:     } else {
                   5600:         my %savedsettings = %curr_group; 
1.809     raeburn  5601:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5602:         my $deloutcome;
                   5603:         if ($result eq 'ok') {
1.809     raeburn  5604:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5605:         } else {
                   5606:             return ('write error',$result);
                   5607:         }
                   5608:         if ($deloutcome eq 'ok') {
                   5609:             return 'ok';
                   5610:         } else {
                   5611:             return ('delete error',$deloutcome);
                   5612:         }
                   5613:     }
                   5614: }
                   5615: 
1.679     raeburn  5616: sub modify_group_roles {
1.957     raeburn  5617:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5618:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5619:     my $role = 'gr/'.&escape($userprivs);
                   5620:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5621:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5622:     if ($result eq 'ok') {
                   5623:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5624:     }
1.679     raeburn  5625:     return $result;
                   5626: }
                   5627: 
                   5628: sub modify_coursegroup_membership {
                   5629:     my ($cdom,$cnum,$membership) = @_;
                   5630:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5631:     return $result;
                   5632: }
                   5633: 
1.682     raeburn  5634: sub get_active_groups {
                   5635:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5636:     my $now = time;
                   5637:     my %groups = ();
                   5638:     foreach my $key (keys(%env)) {
1.811     albertel 5639:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5640:             my ($start,$end) = split(/\./,$env{$key});
                   5641:             if (($end!=0) && ($end<$now)) { next; }
                   5642:             if (($start!=0) && ($start>$now)) { next; }
                   5643:             if ($1 eq $cdom && $2 eq $cnum) {
                   5644:                 $groups{$3} = $env{$key} ;
                   5645:             }
                   5646:         }
                   5647:     }
                   5648:     return %groups;
                   5649: }
                   5650: 
1.683     raeburn  5651: sub get_group_membership {
                   5652:     my ($cdom,$cnum,$group) = @_;
                   5653:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5654: }
                   5655: 
                   5656: sub get_users_groups {
                   5657:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5658:     my @usersgroups;
1.683     raeburn  5659:     my $cachetime=1800;
                   5660: 
                   5661:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5662:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5663:     if (defined($cached)) {
1.734     albertel 5664:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5665:     } else {  
                   5666:         $grouplist = '';
1.816     raeburn  5667:         my $courseurl = &courseid_to_courseurl($courseid);
                   5668:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5669:         my $access_end = $env{'course.'.$courseid.
                   5670:                               '.default_enrollment_end_date'};
                   5671:         my $now = time;
                   5672:         foreach my $key (keys(%roleshash)) {
                   5673:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5674:                 my $group = $1;
                   5675:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5676:                     my $start = $2;
                   5677:                     my $end = $1;
                   5678:                     if ($start == -1) { next; } # deleted from group
                   5679:                     if (($start!=0) && ($start>$now)) { next; }
                   5680:                     if (($end!=0) && ($end<$now)) {
                   5681:                         if ($access_end && $access_end < $now) {
                   5682:                             if ($access_end - $end < 86400) {
                   5683:                                 push(@usersgroups,$group);
1.733     raeburn  5684:                             }
                   5685:                         }
1.817     raeburn  5686:                         next;
1.733     raeburn  5687:                     }
1.817     raeburn  5688:                     push(@usersgroups,$group);
1.683     raeburn  5689:                 }
                   5690:             }
                   5691:         }
1.817     raeburn  5692:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5693:         $grouplist = join(':',@usersgroups);
                   5694:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5695:     }
1.733     raeburn  5696:     return @usersgroups;
1.683     raeburn  5697: }
                   5698: 
                   5699: sub devalidate_getgroups_cache {
                   5700:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5701:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5702: 
1.683     raeburn  5703:     my $hashid="$udom:$uname:$courseid";
                   5704:     &devalidate_cache_new('getgroups',$hashid);
                   5705: }
                   5706: 
1.12      www      5707: # ------------------------------------------------------------------ Plain Text
                   5708: 
                   5709: sub plaintext {
1.988     raeburn  5710:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 5711:     if ($short =~ /^cr/) {
                   5712: 	return (split('/',$short))[-1];
                   5713:     }
1.742     raeburn  5714:     if (!defined($cid)) {
                   5715:         $cid = $env{'request.course.id'};
                   5716:     }
1.988     raeburn  5717:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   5718:         unless ($forcedefault) {
                   5719:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   5720:             &Apache::lonlocal::mt_escape(\$roletext);
                   5721:             return &Apache::lonlocal::mt($roletext);
                   5722:         }
1.742     raeburn  5723:     }
                   5724:     my %rolenames = (
                   5725:                       Course => 'std',
                   5726:                       Group => 'alt1',
                   5727:                     );
                   5728:     if (defined($type) && 
                   5729:          defined($rolenames{$type}) && 
                   5730:          defined($prp{$short}{$rolenames{$type}})) {
                   5731:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5732:     } else {
                   5733:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5734:     }
1.12      www      5735: }
                   5736: 
                   5737: # ----------------------------------------------------------------- Assign Role
                   5738: 
                   5739: sub assignrole {
1.957     raeburn  5740:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5741:         $context)=@_;
1.21      www      5742:     my $mrole;
                   5743:     if ($role =~ /^cr\//) {
1.393     www      5744:         my $cwosec=$url;
1.811     albertel 5745:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5746: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5747:            &logthis('Refused custom assignrole: '.
                   5748:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5749: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5750:            return 'refused'; 
                   5751:         }
1.21      www      5752:         $mrole='cr';
1.678     raeburn  5753:     } elsif ($role =~ /^gr\//) {
                   5754:         my $cwogrp=$url;
1.811     albertel 5755:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5756:         unless (&allowed('mdg',$cwogrp)) {
                   5757:             &logthis('Refused group assignrole: '.
                   5758:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5759:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5760:             return 'refused';
                   5761:         }
                   5762:         $mrole='gr';
1.21      www      5763:     } else {
1.82      www      5764:         my $cwosec=$url;
1.811     albertel 5765:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5766:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5767:             my $refused;
                   5768:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5769:                 if (!(&allowed('c'.$role,$url))) {
                   5770:                     $refused = 1;
                   5771:                 }
                   5772:             } else {
                   5773:                 $refused = 1;
                   5774:             }
1.947     raeburn  5775:             if ($refused) {
                   5776:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5777:                     $refused = '';
                   5778:                 } else {
                   5779:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5780:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5781: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5782:                     return 'refused';
                   5783:                 }
1.932     raeburn  5784:             }
1.104     www      5785:         }
1.21      www      5786:         $mrole=$role;
                   5787:     }
1.620     albertel 5788:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5789:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5790:     if ($end) { $command.='_'.$end; }
1.21      www      5791:     if ($start) {
                   5792: 	if ($end) { 
1.81      www      5793:            $command.='_'.$start; 
1.21      www      5794:         } else {
1.81      www      5795:            $command.='_0_'.$start;
1.21      www      5796:         }
                   5797:     }
1.739     raeburn  5798:     my $origstart = $start;
                   5799:     my $origend = $end;
1.957     raeburn  5800:     my $delflag;
1.357     www      5801: # actually delete
                   5802:     if ($deleteflag) {
1.373     www      5803: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5804: # modify command to delete the role
1.620     albertel 5805:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5806:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5807: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5808: # set start and finish to negative values for userrolelog
                   5809:            $start=-1;
                   5810:            $end=-1;
1.957     raeburn  5811:            $delflag = 1;
1.357     www      5812:         }
                   5813:     }
                   5814: # send command
1.349     www      5815:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5816: # log new user role if status is ok
1.349     www      5817:     if ($answer eq 'ok') {
1.663     raeburn  5818: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5819: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5820:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5821:         unless ($role =~ /^gr/) {
                   5822:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5823:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5824:         }
1.349     www      5825:     }
                   5826:     return $answer;
1.169     harris41 5827: }
                   5828: 
                   5829: # -------------------------------------------------- Modify user authentication
1.197     www      5830: # Overrides without validation
                   5831: 
1.169     harris41 5832: sub modifyuserauth {
                   5833:     my ($udom,$uname,$umode,$upass)=@_;
                   5834:     my $uhome=&homeserver($uname,$udom);
1.197     www      5835:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5836:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5837:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5838:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5839:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5840: 		     &escape($upass),$uhome);
1.620     albertel 5841:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5842:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5843:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5844:     &log($udom,,$uname,$uhome,
1.620     albertel 5845:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5846:                                      $env{'user.name'}.', '.$umode.
1.197     www      5847:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5848:     unless ($reply eq 'ok') {
1.197     www      5849:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5850: 	return 'error: '.$reply;
                   5851:     }   
1.170     harris41 5852:     return 'ok';
1.80      www      5853: }
                   5854: 
1.81      www      5855: # --------------------------------------------------------------- Modify a user
1.80      www      5856: 
1.81      www      5857: sub modifyuser {
1.206     matthew  5858:     my ($udom,    $uname, $uid,
                   5859:         $umode,   $upass, $first,
                   5860:         $middle,  $last,  $gene,
1.963     raeburn  5861:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5862:     $udom= &LONCAPA::clean_domain($udom);
                   5863:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5864:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5865:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5866: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5867:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5868:                                      ' desiredhome not specified'). 
1.620     albertel 5869:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5870:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5871:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5872: # ----------------------------------------------------------------- Create User
1.406     albertel 5873:     if (($uhome eq 'no_host') && 
                   5874: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5875:         my $unhome='';
1.844     albertel 5876:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5877:             $unhome = $desiredhome;
1.620     albertel 5878: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5879: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5880:         } else { # load balancing routine for determining $unhome
1.81      www      5881:             my $loadm=10000000;
1.841     albertel 5882: 	    my %servers = &get_servers($udom,'library');
                   5883: 	    foreach my $tryserver (keys(%servers)) {
                   5884: 		my $answer=reply('load',$tryserver);
                   5885: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5886: 		    $loadm=$answer;
                   5887: 		    $unhome=$tryserver;
                   5888: 		}
1.80      www      5889: 	    }
                   5890:         }
                   5891:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5892: 	    return 'error: unable to find a home server for '.$uname.
                   5893:                    ' in domain '.$udom;
1.80      www      5894:         }
                   5895:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5896:                          &escape($upass),$unhome);
                   5897: 	unless ($reply eq 'ok') {
                   5898:             return 'error: '.$reply;
                   5899:         }   
1.230     stredwic 5900:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5901:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5902: 	    return 'error: unable verify users home machine.';
1.80      www      5903:         }
1.209     matthew  5904:     }   # End of creation of new user
1.80      www      5905: # ---------------------------------------------------------------------- Add ID
                   5906:     if ($uid) {
                   5907:        $uid=~tr/A-Z/a-z/;
                   5908:        my %uidhash=&idrget($udom,$uname);
1.196     www      5909:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5910:          && (!$forceid)) {
1.80      www      5911: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5912: 	      return 'error: user id "'.$uid.'" does not match '.
                   5913:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5914:           }
                   5915:        } else {
                   5916: 	  &idput($udom,($uname => $uid));
                   5917:        }
                   5918:     }
                   5919: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5920:     my @tmp=&get('environment',
1.899     raeburn  5921: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5922:                     'permanentemail','inststatus'],
1.134     albertel 5923: 		   $udom,$uname);
1.313     matthew  5924:     my %names;
                   5925:     if ($tmp[0] =~ m/^error:.*/) { 
                   5926:         %names=(); 
                   5927:     } else {
                   5928:         %names = @tmp;
                   5929:     }
1.388     www      5930: #
                   5931: # Make sure to not trash student environment if instructor does not bother
                   5932: # to supply name and email information
                   5933: #
                   5934:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5935:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5936:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5937:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5938:     if ($email) {
                   5939:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5940:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5941:     }
1.899     raeburn  5942:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  5943:     if (defined($inststatus)) {
                   5944:         $names{'inststatus'} = '';
                   5945:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   5946:         if (ref($usertypes) eq 'HASH') {
                   5947:             my @okstatuses; 
                   5948:             foreach my $item (split(/:/,$inststatus)) {
                   5949:                 if (defined($usertypes->{$item})) {
                   5950:                     push(@okstatuses,$item);  
                   5951:                 }
                   5952:             }
                   5953:             if (@okstatuses) {
                   5954:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   5955:             }
                   5956:         }
                   5957:     }
1.134     albertel 5958:     my $reply = &put('environment', \%names, $udom,$uname);
                   5959:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5960:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5961:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5962:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5963:                  $umode.', '.$first.', '.$middle.', '.
                   5964: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5965:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5966:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5967:     } else {
                   5968:         $logmsg .= ' during self creation';
                   5969:     }
                   5970:     &logthis($logmsg);
1.134     albertel 5971:     return 'ok';
1.80      www      5972: }
                   5973: 
1.81      www      5974: # -------------------------------------------------------------- Modify student
1.80      www      5975: 
1.81      www      5976: sub modifystudent {
                   5977:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5978:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  5979:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 5980:     if (!$cid) {
1.620     albertel 5981: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5982: 	    return 'not_in_class';
                   5983: 	}
1.80      www      5984:     }
                   5985: # --------------------------------------------------------------- Make the user
1.81      www      5986:     my $reply=&modifyuser
1.209     matthew  5987: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  5988:          $desiredhome,$email,$inststatus);
1.80      www      5989:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5990:     # This will cause &modify_student_enrollment to get the uid from the
                   5991:     # students environment
                   5992:     $uid = undef if (!$forceid);
1.455     albertel 5993:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5994: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5995:     return $reply;
                   5996: }
                   5997: 
                   5998: sub modify_student_enrollment {
1.957     raeburn  5999:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6000:     my ($cdom,$cnum,$chome);
                   6001:     if (!$cid) {
1.620     albertel 6002: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6003: 	    return 'not_in_class';
                   6004: 	}
1.620     albertel 6005: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6006: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6007:     } else {
                   6008: 	($cdom,$cnum)=split(/_/,$cid);
                   6009:     }
1.620     albertel 6010:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6011:     if (!$chome) {
1.457     raeburn  6012: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6013:     }
1.455     albertel 6014:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6015:     # Make sure the user exists
1.81      www      6016:     my $uhome=&homeserver($uname,$udom);
                   6017:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6018: 	return 'error: no such user';
                   6019:     }
1.297     matthew  6020:     # Get student data if we were not given enough information
                   6021:     if (!defined($first)  || $first  eq '' || 
                   6022:         !defined($last)   || $last   eq '' || 
                   6023:         !defined($uid)    || $uid    eq '' || 
                   6024:         !defined($middle) || $middle eq '' || 
                   6025:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6026:         # They did not supply us with enough data to enroll the student, so
                   6027:         # we need to pick up more information.
1.297     matthew  6028:         my %tmp = &get('environment',
1.294     matthew  6029:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6030:                        ,$udom,$uname);
                   6031: 
1.800     albertel 6032:         #foreach my $key (keys(%tmp)) {
                   6033:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6034:         #}
1.294     matthew  6035:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6036:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6037:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6038:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6039:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6040:     }
1.556     albertel 6041:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6042:     my $reply=cput('classlist',
                   6043: 		   {"$uname:$udom" => 
1.515     raeburn  6044: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6045: 		   $cdom,$cnum);
1.81      www      6046:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6047: 	return 'error: '.$reply;
1.652     albertel 6048:     } else {
                   6049: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6050:     }
1.297     matthew  6051:     # Add student role to user
1.83      www      6052:     my $uurl='/'.$cid;
1.81      www      6053:     $uurl=~s/\_/\//g;
                   6054:     if ($usec) {
                   6055: 	$uurl.='/'.$usec;
                   6056:     }
1.957     raeburn  6057:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6058: }
                   6059: 
1.556     albertel 6060: sub format_name {
                   6061:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6062:     my $name;
                   6063:     if ($first ne 'lastname') {
                   6064: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6065:     } else {
                   6066: 	if ($lastname=~/\S/) {
                   6067: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6068: 	    $name=~s/\s+,/,/;
                   6069: 	} else {
                   6070: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6071: 	}
                   6072:     }
                   6073:     $name=~s/^\s+//;
                   6074:     $name=~s/\s+$//;
                   6075:     $name=~s/\s+/ /g;
                   6076:     return $name;
                   6077: }
                   6078: 
1.84      www      6079: # ------------------------------------------------- Write to course preferences
                   6080: 
                   6081: sub writecoursepref {
                   6082:     my ($courseid,%prefs)=@_;
                   6083:     $courseid=~s/^\///;
                   6084:     $courseid=~s/\_/\//g;
                   6085:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6086:     my $chome=homeserver($cnum,$cdomain);
                   6087:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6088: 	return 'error: no such course';
                   6089:     }
                   6090:     my $cstring='';
1.800     albertel 6091:     foreach my $pref (keys(%prefs)) {
                   6092: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6093:     }
1.84      www      6094:     $cstring=~s/\&$//;
                   6095:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6096: }
                   6097: 
                   6098: # ---------------------------------------------------------- Make/modify course
                   6099: 
                   6100: sub createcourse {
1.741     raeburn  6101:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6102:         $course_owner,$crstype)=@_;
1.84      www      6103:     $url=&declutter($url);
                   6104:     my $cid='';
1.264     matthew  6105:     unless (&allowed('ccc',$udom)) {
1.84      www      6106:         return 'refused';
                   6107:     }
                   6108: # ------------------------------------------------------------------- Create ID
1.674     www      6109:    my $uname=int(1+rand(9)).
                   6110:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6111:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6112:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6113: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6114:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6115:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6116:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6117:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6118:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6119:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6120:            return 'error: unable to generate unique course-ID';
                   6121:        } 
                   6122:    }
1.264     matthew  6123: # ------------------------------------------------ Check supplied server name
1.620     albertel 6124:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6125:     if (! &is_library($course_server)) {
1.264     matthew  6126:         return 'error:bad server name '.$course_server;
                   6127:     }
1.84      www      6128: # ------------------------------------------------------------- Make the course
                   6129:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6130:                       $course_server);
1.84      www      6131:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6132:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6133:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6134: 	return 'error: no such course';
                   6135:     }
1.271     www      6136: # ----------------------------------------------------------------- Course made
1.516     raeburn  6137: # log existence
1.918     raeburn  6138:     my $newcourse = {
                   6139:                     $udom.'_'.$uname => {
1.921     raeburn  6140:                                      description => $description,
                   6141:                                      inst_code   => $inst_code,
                   6142:                                      owner       => $course_owner,
                   6143:                                      type        => $crstype,
1.918     raeburn  6144:                                                 },
                   6145:                     };
1.921     raeburn  6146:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6147: # set toplevel url
1.271     www      6148:     my $topurl=$url;
                   6149:     unless ($nonstandard) {
                   6150: # ------------------------------------------ For standard courses, make top url
                   6151:         my $mapurl=&clutter($url);
1.278     www      6152:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6153:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6154: <map>
                   6155: <resource id="1" type="start"></resource>
                   6156: <resource id="2" src="$mapurl"></resource>
                   6157: <resource id="3" type="finish"></resource>
                   6158: <link index="1" from="1" to="2"></link>
                   6159: <link index="2" from="2" to="3"></link>
                   6160: </map>
                   6161: ENDINITMAP
                   6162:         $topurl=&declutter(
1.638     albertel 6163:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6164:                           );
                   6165:     }
                   6166: # ----------------------------------------------------------- Write preferences
1.84      www      6167:     &writecoursepref($udom.'_'.$uname,
                   6168:                      ('description' => $description,
1.271     www      6169:                       'url'         => $topurl));
1.84      www      6170:     return '/'.$udom.'/'.$uname;
                   6171: }
                   6172: 
1.813     albertel 6173: sub is_course {
                   6174:     my ($cdom,$cnum) = @_;
                   6175:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6176: 				undef,'.');
1.813     albertel 6177:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6178:         return 1;
                   6179:     }
                   6180:     return 0;
                   6181: }
                   6182: 
1.21      www      6183: # ---------------------------------------------------------- Assign Custom Role
                   6184: 
                   6185: sub assigncustomrole {
1.957     raeburn  6186:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6187:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6188:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6189: }
                   6190: 
                   6191: # ----------------------------------------------------------------- Revoke Role
                   6192: 
                   6193: sub revokerole {
1.957     raeburn  6194:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6195:     my $now=time;
1.965     raeburn  6196:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6197: }
                   6198: 
                   6199: # ---------------------------------------------------------- Revoke Custom Role
                   6200: 
                   6201: sub revokecustomrole {
1.957     raeburn  6202:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6203:     my $now=time;
1.357     www      6204:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6205:            $deleteflag,$selfenroll,$context);
1.17      www      6206: }
                   6207: 
1.533     banghart 6208: # ------------------------------------------------------------ Disk usage
1.535     albertel 6209: sub diskusage {
1.955     raeburn  6210:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6211:     $directorypath =~ s/\/$//;
                   6212:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6213:                        .&escape($getpropath).':'.&escape($uname).':'
                   6214:                        .&escape($udom),homeserver($uname,$udom));
                   6215:     if ($listing eq 'unknown_cmd') {
                   6216:         if ($getpropath) {
                   6217:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6218:         }
                   6219:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6220:     }
1.514     albertel 6221:     return $listing;
1.512     banghart 6222: }
                   6223: 
1.566     banghart 6224: sub is_locked {
                   6225:     my ($file_name, $domain, $user) = @_;
                   6226:     my @check;
                   6227:     my $is_locked;
                   6228:     push @check, $file_name;
1.613     albertel 6229:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6230: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6231:     my ($tmp)=keys(%locked);
                   6232:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6233:     
1.566     banghart 6234:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6235:         $is_locked = 'false';
                   6236:         foreach my $entry (@{$locked{$file_name}}) {
                   6237:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6238:                $is_locked = 'true';
                   6239:                last;
1.745     raeburn  6240:            }
                   6241:        }
1.566     banghart 6242:     } else {
                   6243:         $is_locked = 'false';
                   6244:     }
                   6245: }
                   6246: 
1.759     albertel 6247: sub declutter_portfile {
                   6248:     my ($file) = @_;
1.833     albertel 6249:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6250:     return $file;
                   6251: }
                   6252: 
1.559     banghart 6253: # ------------------------------------------------------------- Mark as Read Only
                   6254: 
                   6255: sub mark_as_readonly {
                   6256:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6257:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6258:     my ($tmp)=keys(%current_permissions);
                   6259:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6260:     foreach my $file (@{$files}) {
1.759     albertel 6261: 	$file = &declutter_portfile($file);
1.561     banghart 6262:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6263:     }
1.613     albertel 6264:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6265:     return;
                   6266: }
                   6267: 
1.572     banghart 6268: # ------------------------------------------------------------Save Selected Files
                   6269: 
                   6270: sub save_selected_files {
                   6271:     my ($user, $path, @files) = @_;
                   6272:     my $filename = $user."savedfiles";
1.573     banghart 6273:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6274:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6275:     foreach my $file (@files) {
1.620     albertel 6276:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6277:     }
                   6278:     foreach my $file (@other_files) {
1.574     banghart 6279:         print (OUT $file."\n");
1.572     banghart 6280:     }
1.574     banghart 6281:     close (OUT);
1.572     banghart 6282:     return 'ok';
                   6283: }
                   6284: 
1.574     banghart 6285: sub clear_selected_files {
                   6286:     my ($user) = @_;
                   6287:     my $filename = $user."savedfiles";
                   6288:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6289:     print (OUT undef);
                   6290:     close (OUT);
                   6291:     return ("ok");    
                   6292: }
                   6293: 
1.572     banghart 6294: sub files_in_path {
                   6295:     my ($user, $path) = @_;
                   6296:     my $filename = $user."savedfiles";
                   6297:     my %return_files;
1.574     banghart 6298:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6299:     while (my $line_in = <IN>) {
1.574     banghart 6300:         chomp ($line_in);
                   6301:         my @paths_and_file = split (m!/!, $line_in);
                   6302:         my $file_part = pop (@paths_and_file);
                   6303:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6304:         $path_part.='/';
                   6305:         my $path_and_file = $path_part.$file_part;
                   6306:         if ($path_part eq $path) {
                   6307:             $return_files{$file_part}= 'selected';
                   6308:         }
                   6309:     }
1.574     banghart 6310:     close (IN);
                   6311:     return (\%return_files);
1.572     banghart 6312: }
                   6313: 
                   6314: # called in portfolio select mode, to show files selected NOT in current directory
                   6315: sub files_not_in_path {
                   6316:     my ($user, $path) = @_;
                   6317:     my $filename = $user."savedfiles";
                   6318:     my @return_files;
                   6319:     my $path_part;
1.800     albertel 6320:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6321:     while (my $line = <IN>) {
1.572     banghart 6322:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6323:         my @paths_and_file = split(m|/|, $line);
                   6324:         my $file_part = pop(@paths_and_file);
                   6325:         chomp($file_part);
                   6326:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6327:         $path_part .= '/';
                   6328:         my $path_and_file = $path_part.$file_part;
                   6329:         if ($path_part ne $path) {
1.800     albertel 6330:             push(@return_files, ($path_and_file));
1.572     banghart 6331:         }
                   6332:     }
1.800     albertel 6333:     close(OUT);
1.574     banghart 6334:     return (@return_files);
1.572     banghart 6335: }
                   6336: 
1.745     raeburn  6337: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6338: 
1.745     raeburn  6339: sub get_portfile_permissions {
                   6340:     my ($domain,$user) = @_;
1.613     albertel 6341:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6342:     my ($tmp)=keys(%current_permissions);
                   6343:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6344:     return \%current_permissions;
                   6345: }
                   6346: 
                   6347: #---------------------------------------------Get portfolio file access controls
                   6348: 
1.749     raeburn  6349: sub get_access_controls {
1.745     raeburn  6350:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6351:     my %access;
                   6352:     my $real_file = $file;
                   6353:     $file =~ s/\.meta$//;
1.745     raeburn  6354:     if (defined($file)) {
1.749     raeburn  6355:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6356:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6357:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6358:             }
                   6359:         }
1.745     raeburn  6360:     } else {
1.749     raeburn  6361:         foreach my $key (keys(%{$current_permissions})) {
                   6362:             if ($key =~ /\0accesscontrol$/) {
                   6363:                 if (defined($group)) {
                   6364:                     if ($key !~ m-^\Q$group\E/-) {
                   6365:                         next;
                   6366:                     }
                   6367:                 }
                   6368:                 my ($fullpath) = split(/\0/,$key);
                   6369:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6370:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6371:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6372:                     }
                   6373:                 }
                   6374:             }
                   6375:         }
                   6376:     }
                   6377:     return %access;
                   6378: }
                   6379: 
                   6380: sub modify_access_controls {
                   6381:     my ($file_name,$changes,$domain,$user)=@_;
                   6382:     my ($outcome,$deloutcome);
                   6383:     my %store_permissions;
                   6384:     my %new_values;
                   6385:     my %new_control;
                   6386:     my %translation;
                   6387:     my @deletions = ();
                   6388:     my $now = time;
                   6389:     if (exists($$changes{'activate'})) {
                   6390:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6391:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6392:             my $numnew = scalar(@newitems);
                   6393:             for (my $i=0; $i<$numnew; $i++) {
                   6394:                 my $newkey = $newitems[$i];
                   6395:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6396:                 if ($newkey =~ /^\d+:/) { 
                   6397:                     $newkey =~ s/^(\d+)/$newid/;
                   6398:                     $translation{$1} = $newid;
                   6399:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6400:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6401:                     $translation{$1} = $newid;
                   6402:                 }
1.749     raeburn  6403:                 $new_values{$file_name."\0".$newkey} = 
                   6404:                                           $$changes{'activate'}{$newitems[$i]};
                   6405:                 $new_control{$newkey} = $now;
                   6406:             }
                   6407:         }
                   6408:     }
                   6409:     my %todelete;
                   6410:     my %changed_items;
                   6411:     foreach my $action ('delete','update') {
                   6412:         if (exists($$changes{$action})) {
                   6413:             if (ref($$changes{$action}) eq 'HASH') {
                   6414:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6415:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6416:                     if ($action eq 'delete') { 
                   6417:                         $todelete{$itemnum} = 1;
                   6418:                     } else {
                   6419:                         $changed_items{$itemnum} = $key;
                   6420:                     }
                   6421:                 }
1.745     raeburn  6422:             }
                   6423:         }
1.749     raeburn  6424:     }
                   6425:     # get lock on access controls for file.
                   6426:     my $lockhash = {
                   6427:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6428:                                                        ':'.$env{'user.domain'},
                   6429:                    }; 
                   6430:     my $tries = 0;
                   6431:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6432:    
                   6433:     while (($gotlock ne 'ok') && $tries <3) {
                   6434:         $tries ++;
                   6435:         sleep 1;
                   6436:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6437:     }
                   6438:     if ($gotlock eq 'ok') {
                   6439:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6440:         my ($tmp)=keys(%curr_permissions);
                   6441:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6442:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6443:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6444:             if (ref($curr_controls) eq 'HASH') {
                   6445:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6446:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6447:                     if (defined($todelete{$itemnum})) {
                   6448:                         push(@deletions,$file_name."\0".$control_item);
                   6449:                     } else {
                   6450:                         if (defined($changed_items{$itemnum})) {
                   6451:                             $new_control{$changed_items{$itemnum}} = $now;
                   6452:                             push(@deletions,$file_name."\0".$control_item);
                   6453:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6454:                         } else {
                   6455:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6456:                         }
                   6457:                     }
1.745     raeburn  6458:                 }
                   6459:             }
                   6460:         }
1.970     raeburn  6461:         my ($group);
                   6462:         if (&is_course($domain,$user)) {
                   6463:             ($group,my $file) = split(/\//,$file_name,2);
                   6464:         }
1.749     raeburn  6465:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6466:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6467:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6468:         #  remove lock
                   6469:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6470:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6471:         my $sqlresult =
1.970     raeburn  6472:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6473:                                     $group);
1.749     raeburn  6474:     } else {
                   6475:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6476:     }
1.749     raeburn  6477:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6478: }
                   6479: 
1.827     raeburn  6480: sub make_public_indefinitely {
                   6481:     my ($requrl) = @_;
                   6482:     my $now = time;
                   6483:     my $action = 'activate';
                   6484:     my $aclnum = 0;
                   6485:     if (&is_portfolio_url($requrl)) {
                   6486:         my (undef,$udom,$unum,$file_name,$group) =
                   6487:             &parse_portfolio_url($requrl);
                   6488:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6489:         my %access_controls = &get_access_controls($current_perms,
                   6490:                                                    $group,$file_name);
                   6491:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6492:             my ($num,$scope,$end,$start) = 
                   6493:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6494:             if ($scope eq 'public') {
                   6495:                 if ($start <= $now && $end == 0) {
                   6496:                     $action = 'none';
                   6497:                 } else {
                   6498:                     $action = 'update';
                   6499:                     $aclnum = $num;
                   6500:                 }
                   6501:                 last;
                   6502:             }
                   6503:         }
                   6504:         if ($action eq 'none') {
                   6505:              return 'ok';
                   6506:         } else {
                   6507:             my %changes;
                   6508:             my $newend = 0;
                   6509:             my $newstart = $now;
                   6510:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6511:             $changes{$action}{$newkey} = {
                   6512:                 type => 'public',
                   6513:                 time => {
                   6514:                     start => $newstart,
                   6515:                     end   => $newend,
                   6516:                 },
                   6517:             };
                   6518:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6519:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6520:             return $outcome;
                   6521:         }
                   6522:     } else {
                   6523:         return 'invalid';
                   6524:     }
                   6525: }
                   6526: 
1.745     raeburn  6527: #------------------------------------------------------Get Marked as Read Only
                   6528: 
                   6529: sub get_marked_as_readonly {
                   6530:     my ($domain,$user,$what,$group) = @_;
                   6531:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6532:     my @readonly_files;
1.629     banghart 6533:     my $cmp1=$what;
                   6534:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6535:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6536:         if (defined($group)) {
                   6537:             if ($file_name !~ m-^\Q$group\E/-) {
                   6538:                 next;
                   6539:             }
                   6540:         }
1.561     banghart 6541:         if (ref($value) eq "ARRAY"){
                   6542:             foreach my $stored_what (@{$value}) {
1.629     banghart 6543:                 my $cmp2=$stored_what;
1.759     albertel 6544:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6545:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6546:                 }
1.629     banghart 6547:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6548:                     push(@readonly_files, $file_name);
1.745     raeburn  6549:                     last;
1.563     banghart 6550:                 } elsif (!defined($what)) {
                   6551:                     push(@readonly_files, $file_name);
1.745     raeburn  6552:                     last;
1.561     banghart 6553:                 }
                   6554:             }
1.745     raeburn  6555:         }
1.561     banghart 6556:     }
                   6557:     return @readonly_files;
                   6558: }
1.577     banghart 6559: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6560: 
1.577     banghart 6561: sub get_marked_as_readonly_hash {
1.745     raeburn  6562:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6563:     my %readonly_files;
1.745     raeburn  6564:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6565:         if (defined($group)) {
                   6566:             if ($file_name !~ m-^\Q$group\E/-) {
                   6567:                 next;
                   6568:             }
                   6569:         }
1.577     banghart 6570:         if (ref($value) eq "ARRAY"){
                   6571:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6572:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6573:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6574:                         if ($lock_descriptor eq 'graded') {
                   6575:                             $readonly_files{$file_name} = 'graded';
                   6576:                         } elsif ($lock_descriptor eq 'handback') {
                   6577:                             $readonly_files{$file_name} = 'handback';
                   6578:                         } else {
                   6579:                             if (!exists($readonly_files{$file_name})) {
                   6580:                                 $readonly_files{$file_name} = 'locked';
                   6581:                             }
                   6582:                         }
1.745     raeburn  6583:                     }
1.750     banghart 6584:                 } 
1.577     banghart 6585:             }
                   6586:         } 
                   6587:     }
                   6588:     return %readonly_files;
                   6589: }
1.559     banghart 6590: # ------------------------------------------------------------ Unmark as Read Only
                   6591: 
                   6592: sub unmark_as_readonly {
1.629     banghart 6593:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6594:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6595:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6596:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6597:     my $symb_crs = $what;
                   6598:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6599:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6600:     my ($tmp)=keys(%current_permissions);
                   6601:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6602:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6603:     foreach my $file (@readonly_files) {
1.759     albertel 6604: 	my $clean_file = &declutter_portfile($file);
                   6605: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6606: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6607:         my @new_locks;
                   6608:         my @del_keys;
                   6609:         if (ref($current_locks) eq "ARRAY"){
                   6610:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6611:                 my $compare=$locker;
1.749     raeburn  6612:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6613:                     $compare=join('',@{$locker});
1.746     raeburn  6614:                     if ($compare ne $symb_crs) {
                   6615:                         push(@new_locks, $locker);
                   6616:                     }
1.563     banghart 6617:                 }
                   6618:             }
1.650     albertel 6619:             if (scalar(@new_locks) > 0) {
1.563     banghart 6620:                 $current_permissions{$file} = \@new_locks;
                   6621:             } else {
                   6622:                 push(@del_keys, $file);
1.613     albertel 6623:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6624:                 delete($current_permissions{$file});
1.563     banghart 6625:             }
                   6626:         }
1.561     banghart 6627:     }
1.613     albertel 6628:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6629:     return;
                   6630: }
1.512     banghart 6631: 
1.17      www      6632: # ------------------------------------------------------------ Directory lister
                   6633: 
                   6634: sub dirlist {
1.955     raeburn  6635:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6636:     $uri=~s/^\///;
                   6637:     $uri=~s/\/$//;
1.253     stredwic 6638:     my ($udom, $uname);
1.955     raeburn  6639:     if ($getuserdir) {
1.253     stredwic 6640:         $udom = $userdomain;
                   6641:         $uname = $username;
1.955     raeburn  6642:     } else {
                   6643:         (undef,$udom,$uname)=split(/\//,$uri);
                   6644:         if(defined($userdomain)) {
                   6645:             $udom = $userdomain;
                   6646:         }
                   6647:         if(defined($username)) {
                   6648:             $uname = $username;
                   6649:         }
1.253     stredwic 6650:     }
1.955     raeburn  6651:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6652: 
1.955     raeburn  6653:     $dirRoot = $perlvar{'lonDocRoot'};
                   6654:     if (defined($getpropath)) {
                   6655:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6656:         $dirRoot =~ s/\/$//;
1.955     raeburn  6657:     } elsif (defined($getuserdir)) {
                   6658:         my $subdir=$uname.'__';
                   6659:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6660:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6661:                    ."/$udom/$subdir/$uname";
                   6662:     } elsif (defined($alternateRoot)) {
                   6663:         $dirRoot = $alternateRoot;
1.751     banghart 6664:     }
1.253     stredwic 6665: 
                   6666:     if($udom) {
                   6667:         if($uname) {
1.955     raeburn  6668:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6669:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6670:                               .':'.&escape($uname).':'.&escape($udom),
                   6671:                               &homeserver($uname,$udom));
                   6672:             if ($listing eq 'unknown_cmd') {
                   6673:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6674:                                   &homeserver($uname,$udom));
                   6675:             } else {
                   6676:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6677:             }
1.605     matthew  6678:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6679:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6680: 				  &homeserver($uname,$udom));
1.605     matthew  6681:                 @listing_results = split(/:/,$listing);
                   6682:             } else {
                   6683:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6684:             }
                   6685:             return @listing_results;
1.955     raeburn  6686:         } elsif(!$alternateRoot) {
1.800     albertel 6687:             my %allusers;
1.841     albertel 6688: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6689:  	    foreach my $tryserver (keys(%servers)) {
                   6690:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6691:                                   &escape($udom),$tryserver);
                   6692:                 if ($listing eq 'unknown_cmd') {
                   6693: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6694: 				      $udom, $tryserver);
                   6695:                 } else {
                   6696:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6697:                 }
1.841     albertel 6698: 		if ($listing eq 'unknown_cmd') {
                   6699: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6700: 				      $udom, $tryserver);
                   6701: 		    @listing_results = split(/:/,$listing);
                   6702: 		} else {
                   6703: 		    @listing_results =
                   6704: 			map { &unescape($_); } split(/:/,$listing);
                   6705: 		}
                   6706: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6707: 		    $listing_results[0] ne 'empty'       &&
                   6708: 		    $listing_results[0] ne 'con_lost') {
                   6709: 		    foreach my $line (@listing_results) {
                   6710: 			my ($entry) = split(/&/,$line,2);
                   6711: 			$allusers{$entry} = 1;
                   6712: 		    }
                   6713: 		}
1.253     stredwic 6714:             }
                   6715:             my $alluserstr='';
1.800     albertel 6716:             foreach my $user (sort(keys(%allusers))) {
                   6717:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6718:             }
                   6719:             $alluserstr=~s/:$//;
                   6720:             return split(/:/,$alluserstr);
                   6721:         } else {
1.800     albertel 6722:             return ('missing user name');
1.253     stredwic 6723:         }
1.955     raeburn  6724:     } elsif(!defined($getpropath)) {
1.841     albertel 6725:         my @all_domains = sort(&all_domains());
1.955     raeburn  6726:         foreach my $domain (@all_domains) {
                   6727:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6728:         }
                   6729:         return @all_domains;
                   6730:     } else {
1.800     albertel 6731:         return ('missing domain');
1.275     stredwic 6732:     }
                   6733: }
                   6734: 
                   6735: # --------------------------------------------- GetFileTimestamp
                   6736: # This function utilizes dirlist and returns the date stamp for
                   6737: # when it was last modified.  It will also return an error of -1
                   6738: # if an error occurs
                   6739: 
                   6740: sub GetFileTimestamp {
1.955     raeburn  6741:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6742:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6743:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6744:     my ($fileStat) = 
                   6745:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6746:                                  undef,$getuserdir);
1.275     stredwic 6747:     my @stats = split('&', $fileStat);
                   6748:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6749:         # @stats contains first the filename, then the stat output
                   6750:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6751:     } else {
                   6752:         return -1;
1.253     stredwic 6753:     }
1.26      www      6754: }
                   6755: 
1.712     albertel 6756: sub stat_file {
                   6757:     my ($uri) = @_;
1.787     albertel 6758:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6759: 
1.955     raeburn  6760:     my ($udom,$uname,$file);
1.712     albertel 6761:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6762: 	($udom,$uname,$file) =
1.811     albertel 6763: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6764: 	$file = 'userfiles/'.$file;
                   6765:     }
                   6766:     if ($uri =~ m-^/res/-) {
                   6767: 	($udom,$uname) = 
1.807     albertel 6768: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6769: 	$file = $uri;
                   6770:     }
                   6771: 
                   6772:     if (!$udom || !$uname || !$file) {
                   6773: 	# unable to handle the uri
                   6774: 	return ();
                   6775:     }
1.956     raeburn  6776:     my $getpropath;
                   6777:     if ($file =~ /^userfiles\//) {
                   6778:         $getpropath = 1;
                   6779:     }
1.955     raeburn  6780:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6781:     my @stats = split('&', $result);
1.721     banghart 6782:     
1.712     albertel 6783:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6784: 	shift(@stats); #filename is first
                   6785: 	return @stats;
                   6786:     }
                   6787:     return ();
                   6788: }
                   6789: 
1.26      www      6790: # -------------------------------------------------------- Value of a Condition
                   6791: 
1.713     albertel 6792: # gets the value of a specific preevaluated condition
                   6793: #    stored in the string  $env{user.state.<cid>}
                   6794: # or looks up a condition reference in the bighash and if if hasn't
                   6795: # already been evaluated recurses into docondval to get the value of
                   6796: # the condition, then memoizing it to 
                   6797: #   $env{user.state.<cid>.<condition>}
1.40      www      6798: sub directcondval {
                   6799:     my $number=shift;
1.620     albertel 6800:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6801: 	&Apache::lonuserstate::evalstate();
                   6802:     }
1.713     albertel 6803:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6804: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6805:     } elsif ($number =~ /^_/) {
                   6806: 	my $sub_condition;
                   6807: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6808: 		&GDBM_READER(),0640)) {
                   6809: 	    $sub_condition=$bighash{'conditions'.$number};
                   6810: 	    untie(%bighash);
                   6811: 	}
                   6812: 	my $value = &docondval($sub_condition);
1.949     raeburn  6813: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6814: 	return $value;
                   6815:     }
1.620     albertel 6816:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6817:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6818:     } else {
                   6819:        return 2;
                   6820:     }
                   6821: }
                   6822: 
1.713     albertel 6823: # get the collection of conditions for this resource
1.26      www      6824: sub condval {
                   6825:     my $condidx=shift;
1.54      www      6826:     my $allpathcond='';
1.713     albertel 6827:     foreach my $cond (split(/\|/,$condidx)) {
                   6828: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6829: 	    $allpathcond.=
                   6830: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6831: 	}
1.191     harris41 6832:     }
1.54      www      6833:     $allpathcond=~s/\|$//;
1.713     albertel 6834:     return &docondval($allpathcond);
                   6835: }
                   6836: 
                   6837: #evaluates an expression of conditions
                   6838: sub docondval {
                   6839:     my ($allpathcond) = @_;
                   6840:     my $result=0;
                   6841:     if ($env{'request.course.id'}
                   6842: 	&& defined($allpathcond)) {
                   6843: 	my $operand='|';
                   6844: 	my @stack;
                   6845: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6846: 	    if ($chunk eq '(') {
                   6847: 		push @stack,($operand,$result);
                   6848: 	    } elsif ($chunk eq ')') {
                   6849: 		my $before=pop @stack;
                   6850: 		if (pop @stack eq '&') {
                   6851: 		    $result=$result>$before?$before:$result;
                   6852: 		} else {
                   6853: 		    $result=$result>$before?$result:$before;
                   6854: 		}
                   6855: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6856: 		$operand=$chunk;
                   6857: 	    } else {
                   6858: 		my $new=directcondval($chunk);
                   6859: 		if ($operand eq '&') {
                   6860: 		    $result=$result>$new?$new:$result;
                   6861: 		} else {
                   6862: 		    $result=$result>$new?$result:$new;
                   6863: 		}
                   6864: 	    }
                   6865: 	}
1.26      www      6866:     }
                   6867:     return $result;
1.421     albertel 6868: }
                   6869: 
                   6870: # ---------------------------------------------------- Devalidate courseresdata
                   6871: 
                   6872: sub devalidatecourseresdata {
                   6873:     my ($coursenum,$coursedomain)=@_;
                   6874:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6875:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6876: }
                   6877: 
1.763     www      6878: 
1.200     www      6879: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6880: #
                   6881: #  Parameters:
                   6882: #      $coursenum    - Number of the course.
                   6883: #      $coursedomain - Domain at which the course was created.
                   6884: #  Returns:
                   6885: #     A hash of the course parameters along (I think) with timestamps
                   6886: #     and version info.
1.877     foxr     6887: 
1.624     albertel 6888: sub get_courseresdata {
                   6889:     my ($coursenum,$coursedomain)=@_;
1.200     www      6890:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6891:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6892:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6893:     my %dumpreply;
1.417     albertel 6894:     unless (defined($cached)) {
1.624     albertel 6895: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6896: 	$result=\%dumpreply;
1.251     albertel 6897: 	my ($tmp) = keys(%dumpreply);
                   6898: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6899: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6900: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6901: 	    return $tmp;
1.416     albertel 6902: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6903: 	    $result=undef;
1.599     albertel 6904: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6905: 	}
                   6906:     }
1.624     albertel 6907:     return $result;
                   6908: }
                   6909: 
1.633     albertel 6910: sub devalidateuserresdata {
                   6911:     my ($uname,$udom)=@_;
                   6912:     my $hashid="$udom:$uname";
                   6913:     &devalidate_cache_new('userres',$hashid);
                   6914: }
                   6915: 
1.624     albertel 6916: sub get_userresdata {
                   6917:     my ($uname,$udom)=@_;
                   6918:     #most student don\'t have any data set, check if there is some data
                   6919:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6920: 
                   6921:     my $hashid="$udom:$uname";
                   6922:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6923:     if (!defined($cached)) {
                   6924: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6925: 	$result=\%resourcedata;
                   6926: 	&do_cache_new('userres',$hashid,$result,600);
                   6927:     }
                   6928:     my ($tmp)=keys(%$result);
                   6929:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6930: 	return $result;
                   6931:     }
                   6932:     #error 2 occurs when the .db doesn't exist
                   6933:     if ($tmp!~/error: 2 /) {
1.672     albertel 6934: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6935: 		 " Trying to get resource data for ".
                   6936: 		 $uname." at ".$udom.": ".
                   6937: 		 $tmp."</font>");
                   6938:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6939: 	#&EXT_cache_set($udom,$uname);
                   6940: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6941: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6942:     }
                   6943:     return $tmp;
                   6944: }
1.879     foxr     6945: #----------------------------------------------- resdata - return resource data
                   6946: #  Purpose:
                   6947: #    Return resource data for either users or for a course.
                   6948: #  Parameters:
                   6949: #     $name      - Course/user name.
                   6950: #     $domain    - Name of the domain the user/course is registered on.
                   6951: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6952: #     @which     - Array of names of resources desired.
                   6953: #  Returns:
                   6954: #     The value of the first reasource in @which that is found in the
                   6955: #     resource hash.
                   6956: #  Exceptional Conditions:
                   6957: #     If the $type passed in is not valid (not the string 'course' or 
                   6958: #     'user', an undefined  reference is returned.
                   6959: #     If none of the resources are found, an undef is returned
1.624     albertel 6960: sub resdata {
                   6961:     my ($name,$domain,$type,@which)=@_;
                   6962:     my $result;
                   6963:     if ($type eq 'course') {
                   6964: 	$result=&get_courseresdata($name,$domain);
                   6965:     } elsif ($type eq 'user') {
                   6966: 	$result=&get_userresdata($name,$domain);
                   6967:     }
                   6968:     if (!ref($result)) { return $result; }    
1.251     albertel 6969:     foreach my $item (@which) {
1.927     albertel 6970: 	if (defined($result->{$item->[0]})) {
                   6971: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6972: 	}
1.250     albertel 6973:     }
1.291     albertel 6974:     return undef;
1.200     www      6975: }
                   6976: 
1.379     matthew  6977: #
                   6978: # EXT resource caching routines
                   6979: #
                   6980: 
                   6981: sub clear_EXT_cache_status {
1.383     albertel 6982:     &delenv('cache.EXT.');
1.379     matthew  6983: }
                   6984: 
                   6985: sub EXT_cache_status {
                   6986:     my ($target_domain,$target_user) = @_;
1.383     albertel 6987:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6988:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6989:         # We know already the user has no data
                   6990:         return 1;
                   6991:     } else {
                   6992:         return 0;
                   6993:     }
                   6994: }
                   6995: 
                   6996: sub EXT_cache_set {
                   6997:     my ($target_domain,$target_user) = @_;
1.383     albertel 6998:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6999:     #&appenv({$cachename => time});
1.379     matthew  7000: }
                   7001: 
1.28      www      7002: # --------------------------------------------------------- Value of a Variable
1.58      www      7003: sub EXT {
1.715     albertel 7004: 
1.395     albertel 7005:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7006:     unless ($varname) { return ''; }
1.218     albertel 7007:     #get real user name/domain, courseid and symb
                   7008:     my $courseid;
1.359     albertel 7009:     my $publicuser;
1.427     www      7010:     if ($symbparm) {
                   7011: 	$symbparm=&get_symb_from_alias($symbparm);
                   7012:     }
1.218     albertel 7013:     if (!($uname && $udom)) {
1.790     albertel 7014:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7015:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7016:     } else {
1.620     albertel 7017: 	$courseid=$env{'request.course.id'};
1.218     albertel 7018:     }
1.48      www      7019:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7020:     my $rest;
1.320     albertel 7021:     if (defined($therest[0])) {
1.48      www      7022:        $rest=join('.',@therest);
                   7023:     } else {
                   7024:        $rest='';
                   7025:     }
1.320     albertel 7026: 
1.57      www      7027:     my $qualifierrest=$qualifier;
                   7028:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7029:     my $spacequalifierrest=$space;
                   7030:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7031:     if ($realm eq 'user') {
1.48      www      7032: # --------------------------------------------------------------- user.resource
                   7033: 	if ($space eq 'resource') {
1.651     albertel 7034: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7035: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7036: 		 &&
1.744     albertel 7037: 		 ($symbparm eq &symbread()) ) {	
                   7038: 		# if we are in the middle of processing the resource the
                   7039: 		# get the value we are planning on committing
                   7040:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7041:                     return $Apache::lonhomework::results{$qualifierrest};
                   7042:                 } else {
                   7043:                     return $Apache::lonhomework::history{$qualifierrest};
                   7044:                 }
1.335     albertel 7045: 	    } else {
1.359     albertel 7046: 		my %restored;
1.620     albertel 7047: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7048: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7049: 		} else {
                   7050: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7051: 		}
1.335     albertel 7052: 		return $restored{$qualifierrest};
                   7053: 	    }
1.48      www      7054: # ----------------------------------------------------------------- user.access
                   7055:         } elsif ($space eq 'access') {
1.218     albertel 7056: 	    # FIXME - not supporting calls for a specific user
1.48      www      7057:             return &allowed($qualifier,$rest);
                   7058: # ------------------------------------------ user.preferences, user.environment
                   7059:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7060: 	    if (($uname eq $env{'user.name'}) &&
                   7061: 		($udom eq $env{'user.domain'})) {
                   7062: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7063: 	    } else {
1.359     albertel 7064: 		my %returnhash;
                   7065: 		if (!$publicuser) {
                   7066: 		    %returnhash=&userenvironment($udom,$uname,
                   7067: 						 $qualifierrest);
                   7068: 		}
1.218     albertel 7069: 		return $returnhash{$qualifierrest};
                   7070: 	    }
1.48      www      7071: # ----------------------------------------------------------------- user.course
                   7072:         } elsif ($space eq 'course') {
1.218     albertel 7073: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7074:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7075: # ------------------------------------------------------------------- user.role
                   7076:         } elsif ($space eq 'role') {
1.218     albertel 7077: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7078:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7079:             if ($qualifier eq 'value') {
                   7080: 		return $role;
                   7081:             } elsif ($qualifier eq 'extent') {
                   7082:                 return $where;
                   7083:             }
                   7084: # ----------------------------------------------------------------- user.domain
                   7085:         } elsif ($space eq 'domain') {
1.218     albertel 7086:             return $udom;
1.48      www      7087: # ------------------------------------------------------------------- user.name
                   7088:         } elsif ($space eq 'name') {
1.218     albertel 7089:             return $uname;
1.48      www      7090: # ---------------------------------------------------- Any other user namespace
1.29      www      7091:         } else {
1.359     albertel 7092: 	    my %reply;
                   7093: 	    if (!$publicuser) {
                   7094: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7095: 	    }
                   7096: 	    return $reply{$qualifierrest};
1.48      www      7097:         }
1.236     www      7098:     } elsif ($realm eq 'query') {
                   7099: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7100:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7101: 						[$spacequalifierrest]);
1.620     albertel 7102: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7103:    } elsif ($realm eq 'request') {
1.48      www      7104: # ------------------------------------------------------------- request.browser
                   7105:         if ($space eq 'browser') {
1.430     www      7106: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7107: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7108: 		    return 1;
                   7109: 		} else {
                   7110: 		    return 0;
                   7111: 		}
                   7112: 	    } else {
1.620     albertel 7113: 		return $env{'browser.'.$qualifier};
1.430     www      7114: 	    }
1.57      www      7115: # ------------------------------------------------------------ request.filename
                   7116:         } else {
1.620     albertel 7117:             return $env{'request.'.$spacequalifierrest};
1.29      www      7118:         }
1.28      www      7119:     } elsif ($realm eq 'course') {
1.48      www      7120: # ---------------------------------------------------------- course.description
1.620     albertel 7121:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7122:     } elsif ($realm eq 'resource') {
1.165     www      7123: 
1.620     albertel 7124: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7125: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7126: 	}
1.693     albertel 7127: 
                   7128: 	if ($space eq 'title') {
                   7129: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7130: 	    return &gettitle($symbparm);
                   7131: 	}
                   7132: 	
                   7133: 	if ($space eq 'map') {
                   7134: 	    my ($map) = &decode_symb($symbparm);
                   7135: 	    return &symbread($map);
                   7136: 	}
1.905     albertel 7137: 	if ($space eq 'filename') {
                   7138: 	    if ($symbparm) {
                   7139: 		return &clutter((&decode_symb($symbparm))[2]);
                   7140: 	    }
                   7141: 	    return &hreflocation('',$env{'request.filename'});
                   7142: 	}
1.693     albertel 7143: 
                   7144: 	my ($section, $group, @groups);
1.593     albertel 7145: 	my ($courselevelm,$courselevel);
1.539     albertel 7146: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7147: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7148: 
1.218     albertel 7149: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7150: 
1.60      www      7151: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7152: 	    my $symbp=$symbparm;
1.735     albertel 7153: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7154: 
                   7155: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7156: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7157: 
1.620     albertel 7158: 	    if (($env{'user.name'} eq $uname) &&
                   7159: 		($env{'user.domain'} eq $udom)) {
                   7160: 		$section=$env{'request.course.sec'};
1.733     raeburn  7161:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7162:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7163: 	    } else {
1.539     albertel 7164: 		if (! defined($usection)) {
1.551     albertel 7165: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7166: 		} else {
                   7167: 		    $section = $usection;
                   7168: 		}
1.733     raeburn  7169:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7170: 	    }
                   7171: 
                   7172: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7173: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7174: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7175: 
1.593     albertel 7176: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7177: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7178: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7179: 
1.60      www      7180: # ----------------------------------------------------------- first, check user
1.624     albertel 7181: 
                   7182: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7183: 				       ([$courselevelr,'resource'],
                   7184: 					[$courselevelm,'map'     ],
                   7185: 					[$courselevel, 'course'  ]));
1.931     albertel 7186: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7187: 
1.594     albertel 7188: # ------------------------------------------------ second, check some of course
1.684     raeburn  7189:             my $coursereply;
1.691     raeburn  7190:             if (@groups > 0) {
                   7191:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7192:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7193:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7194:             }
1.96      www      7195: 
1.684     raeburn  7196: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7197: 				  $env{'course.'.$courseid.'.domain'},
                   7198: 				  'course',
                   7199: 				  ([$seclevelr,   'resource'],
                   7200: 				   [$seclevelm,   'map'     ],
                   7201: 				   [$seclevel,    'course'  ],
                   7202: 				   [$courselevelr,'resource']));
                   7203: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7204: 
1.60      www      7205: # ------------------------------------------------------ third, check map parms
1.218     albertel 7206: 	    my %parmhash=();
                   7207: 	    my $thisparm='';
                   7208: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7209: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7210: 		    &GDBM_READER(),0640)) {
1.218     albertel 7211: 		$thisparm=$parmhash{$symbparm};
                   7212: 		untie(%parmhash);
                   7213: 	    }
1.927     albertel 7214: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7215: 	}
1.594     albertel 7216: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7217: 
1.218     albertel 7218: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7219: 	my $filename;
                   7220: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7221: 	if ($symbparm) {
1.409     www      7222: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7223: 	} else {
1.620     albertel 7224: 	    $filename=$env{'request.filename'};
1.282     albertel 7225: 	}
                   7226: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7227: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7228: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7229: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7230: 
1.927     albertel 7231: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7232: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7233: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7234: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7235: 				     $env{'course.'.$courseid.'.domain'},
                   7236: 				     'course',
1.927     albertel 7237: 				     ([$courselevelm,'map'   ],
                   7238: 				      [$courselevel, 'course']));
                   7239: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7240: 	}
1.145     www      7241: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7242: 	unless ($space eq '0') {
1.336     albertel 7243: 	    my @parts=split(/_/,$space);
                   7244: 	    my $id=pop(@parts);
                   7245: 	    my $part=join('_',@parts);
                   7246: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7247: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7248: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7249: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7250: 	}
1.395     albertel 7251: 	if ($recurse) { return undef; }
                   7252: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7253: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7254: # ---------------------------------------------------- Any other user namespace
                   7255:     } elsif ($realm eq 'environment') {
                   7256: # ----------------------------------------------------------------- environment
1.620     albertel 7257: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7258: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7259: 	} else {
1.770     albertel 7260: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7261: 		return '';
                   7262: 	    }
1.219     albertel 7263: 	    my %returnhash=&userenvironment($udom,$uname,
                   7264: 					    $spacequalifierrest);
                   7265: 	    return $returnhash{$spacequalifierrest};
                   7266: 	}
1.28      www      7267:     } elsif ($realm eq 'system') {
1.48      www      7268: # ----------------------------------------------------------------- system.time
                   7269: 	if ($space eq 'time') {
                   7270: 	    return time;
                   7271:         }
1.696     albertel 7272:     } elsif ($realm eq 'server') {
                   7273: # ----------------------------------------------------------------- system.time
                   7274: 	if ($space eq 'name') {
                   7275: 	    return $ENV{'SERVER_NAME'};
                   7276:         }
1.28      www      7277:     }
1.48      www      7278:     return '';
1.61      www      7279: }
                   7280: 
1.927     albertel 7281: sub get_reply {
                   7282:     my ($reply_value) = @_;
1.940     raeburn  7283:     if (ref($reply_value) eq 'ARRAY') {
                   7284:         if (wantarray) {
                   7285: 	    return @$reply_value;
                   7286:         }
                   7287:         return $reply_value->[0];
                   7288:     } else {
                   7289:         return $reply_value;
1.927     albertel 7290:     }
                   7291: }
                   7292: 
1.691     raeburn  7293: sub check_group_parms {
                   7294:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7295:     my @groupitems = ();
                   7296:     my $resultitem;
1.927     albertel 7297:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7298:     foreach my $group (@{$groups}) {
                   7299:         foreach my $level (@levels) {
1.927     albertel 7300:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7301:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7302:         }
                   7303:     }
                   7304:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7305:                             $env{'course.'.$courseid.'.domain'},
                   7306:                                      'course',@groupitems);
                   7307:     return $coursereply;
                   7308: }
                   7309: 
                   7310: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7311:     my ($courseid,@groups) = @_;
                   7312:     @groups = sort(@groups);
1.691     raeburn  7313:     return @groups;
                   7314: }
                   7315: 
1.395     albertel 7316: sub packages_tab_default {
                   7317:     my ($uri,$varname)=@_;
                   7318:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7319: 
                   7320:     my (@extension,@specifics,$do_default);
                   7321:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7322: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7323: 	if ($pack_type eq 'default') {
                   7324: 	    $do_default=1;
                   7325: 	} elsif ($pack_type eq 'extension') {
                   7326: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7327: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7328: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7329: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7330: 	}
                   7331:     }
                   7332:     # first look for a package that matches the requested part id
                   7333:     foreach my $package (@specifics) {
                   7334: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7335: 	next if ($pack_part ne $part);
                   7336: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7337: 	    return $packagetab{"$pack_type&$name&default"};
                   7338: 	}
                   7339:     }
                   7340:     # look for any possible matching non extension_ package
                   7341:     foreach my $package (@specifics) {
                   7342: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7343: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7344: 	    return $packagetab{"$pack_type&$name&default"};
                   7345: 	}
1.585     albertel 7346: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7347: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7348: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7349: 	}
                   7350:     }
1.738     albertel 7351:     # look for any posible extension_ match
                   7352:     foreach my $package (@extension) {
                   7353: 	my ($package,$pack_type)=@{$package};
                   7354: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7355: 	    return $packagetab{"$pack_type&$name&default"};
                   7356: 	}
                   7357: 	if (defined($packagetab{$package."&$name&default"})) {
                   7358: 	    return $packagetab{$package."&$name&default"};
                   7359: 	}
                   7360:     }
                   7361:     # look for a global default setting
                   7362:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7363: 	return $packagetab{"default&$name&default"};
                   7364:     }
1.395     albertel 7365:     return undef;
                   7366: }
                   7367: 
1.334     albertel 7368: sub add_prefix_and_part {
                   7369:     my ($prefix,$part)=@_;
                   7370:     my $keyroot;
                   7371:     if (defined($prefix) && $prefix !~ /^__/) {
                   7372: 	# prefix that has a part already
                   7373: 	$keyroot=$prefix;
                   7374:     } elsif (defined($prefix)) {
                   7375: 	# prefix that is missing a part
                   7376: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7377:     } else {
                   7378: 	# no prefix at all
                   7379: 	if (defined($part)) { $keyroot='_'.$part; }
                   7380:     }
                   7381:     return $keyroot;
                   7382: }
                   7383: 
1.71      www      7384: # ---------------------------------------------------------------- Get metadata
                   7385: 
1.599     albertel 7386: my %metaentry;
1.71      www      7387: sub metadata {
1.176     www      7388:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7389:     $uri=&declutter($uri);
1.288     albertel 7390:     # if it is a non metadata possible uri return quickly
1.529     albertel 7391:     if (($uri eq '') || 
                   7392: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7393: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7394:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7395: 	return undef;
                   7396:     }
                   7397:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7398: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7399: 	return undef;
1.288     albertel 7400:     }
1.73      www      7401:     my $filename=$uri;
                   7402:     $uri=~s/\.meta$//;
1.172     www      7403: #
                   7404: # Is the metadata already cached?
1.177     www      7405: # Look at timestamp of caching
1.172     www      7406: # Everything is cached by the main uri, libraries are never directly cached
                   7407: #
1.428     albertel 7408:     if (!defined($liburi)) {
1.599     albertel 7409: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7410: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7411:     }
                   7412:     {
1.172     www      7413: #
                   7414: # Is this a recursive call for a library?
                   7415: #
1.599     albertel 7416: #	if (! exists($metacache{$uri})) {
                   7417: #	    $metacache{$uri}={};
                   7418: #	}
1.924     albertel 7419: 	my $cachetime = 60*60;
1.171     www      7420:         if ($liburi) {
                   7421: 	    $liburi=&declutter($liburi);
                   7422:             $filename=$liburi;
1.401     bowersj2 7423:         } else {
1.599     albertel 7424: 	    &devalidate_cache_new('meta',$uri);
                   7425: 	    undef(%metaentry);
1.401     bowersj2 7426: 	}
1.140     www      7427:         my %metathesekeys=();
1.73      www      7428:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7429: 	my $metastring;
1.924     albertel 7430: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7431: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7432: 	    $metastring = 
1.929     albertel 7433: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7434: 					  ('grade_target' => 'meta'));
                   7435: 	    $cachetime = 1; # only want this cached in the child not long term
                   7436: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7437: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7438: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7439: 	    $metastring=&getfile($file);
1.489     albertel 7440: 	}
1.208     albertel 7441:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7442:         my $token;
1.140     www      7443:         undef %metathesekeys;
1.71      www      7444:         while ($token=$parser->get_token) {
1.339     albertel 7445: 	    if ($token->[0] eq 'S') {
                   7446: 		if (defined($token->[2]->{'package'})) {
1.172     www      7447: #
                   7448: # This is a package - get package info
                   7449: #
1.339     albertel 7450: 		    my $package=$token->[2]->{'package'};
                   7451: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7452: 		    if (defined($token->[2]->{'id'})) { 
                   7453: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7454: 		    }
1.599     albertel 7455: 		    if ($metaentry{':packages'}) {
                   7456: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7457: 		    } else {
1.599     albertel 7458: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7459: 		    }
1.736     albertel 7460: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7461: 			my $part=$keyroot;
                   7462: 			$part=~s/^\_//;
1.736     albertel 7463: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7464: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7465: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7466: 			    # ignore package.tab specified default values
                   7467:                             # here &package_tab_default() will fetch those
                   7468: 			    if ($subp eq 'default') { next; }
1.736     albertel 7469: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7470: 			    my $unikey;
                   7471: 			    if ($pack =~ /_0$/) {
                   7472: 				$unikey='parameter_0_'.$name;
                   7473: 				$part=0;
                   7474: 			    } else {
                   7475: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7476: 			    }
1.339     albertel 7477: 			    if ($subp eq 'display') {
                   7478: 				$value.=' [Part: '.$part.']';
                   7479: 			    }
1.599     albertel 7480: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7481: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7482: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7483: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7484: 			    }
1.599     albertel 7485: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7486: 				$metaentry{':'.$unikey}=
                   7487: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7488: 			    }
1.339     albertel 7489: 			}
                   7490: 		    }
                   7491: 		} else {
1.172     www      7492: #
                   7493: # This is not a package - some other kind of start tag
1.339     albertel 7494: #
                   7495: 		    my $entry=$token->[1];
                   7496: 		    my $unikey;
                   7497: 		    if ($entry eq 'import') {
                   7498: 			$unikey='';
                   7499: 		    } else {
                   7500: 			$unikey=$entry;
                   7501: 		    }
                   7502: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7503: 
                   7504: 		    if (defined($token->[2]->{'id'})) { 
                   7505: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7506: 		    }
1.175     www      7507: 
1.339     albertel 7508: 		    if ($entry eq 'import') {
1.175     www      7509: #
                   7510: # Importing a library here
1.339     albertel 7511: #
                   7512: 			if ($depthcount<20) {
                   7513: 			    my $location=$parser->get_text('/import');
                   7514: 			    my $dir=$filename;
                   7515: 			    $dir=~s|[^/]*$||;
                   7516: 			    $location=&filelocation($dir,$location);
1.736     albertel 7517: 			    my $metadata = 
                   7518: 				&metadata($uri,'keys', $location,$unikey,
                   7519: 					  $depthcount+1);
                   7520: 			    foreach my $meta (split(',',$metadata)) {
                   7521: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7522: 				$metathesekeys{$meta}=1;
1.339     albertel 7523: 			    }
                   7524: 			}
                   7525: 		    } else { 
                   7526: 			
                   7527: 			if (defined($token->[2]->{'name'})) { 
                   7528: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7529: 			}
                   7530: 			$metathesekeys{$unikey}=1;
1.736     albertel 7531: 			foreach my $param (@{$token->[3]}) {
                   7532: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7533: 				$token->[2]->{$param};
1.339     albertel 7534: 			}
                   7535: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7536: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7537: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7538: 		 # only ws inside the tag, and not in default, so use default
                   7539: 		 # as value
1.599     albertel 7540: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7541: 			} elsif ( $internaltext =~ /\S/ ) {
                   7542: 		  # something interesting inside the tag
                   7543: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7544: 			} else {
1.908     albertel 7545: 		  # no interesting values, don't set a default
1.339     albertel 7546: 			}
1.172     www      7547: # end of not-a-package not-a-library import
1.339     albertel 7548: 		    }
1.172     www      7549: # end of not-a-package start tag
1.339     albertel 7550: 		}
1.172     www      7551: # the next is the end of "start tag"
1.339     albertel 7552: 	    }
                   7553: 	}
1.483     albertel 7554: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7555: 	$extension = lc($extension);
                   7556: 	if ($extension eq 'htm') { $extension='html'; }
                   7557: 
1.737     albertel 7558: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7559: 	    #no specific packages #how's our extension
                   7560: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7561: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7562: 					 \%metathesekeys);
                   7563: 	}
1.883     albertel 7564: 
                   7565: 	if (!exists($metaentry{':packages'})
                   7566: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7567: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7568: 		#no specific packages well let's get default then
                   7569: 		if ($key!~/^default&/) { next; }
1.488     albertel 7570: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7571: 					     \%metathesekeys);
                   7572: 	    }
                   7573: 	}
1.338     www      7574: # are there custom rights to evaluate
1.599     albertel 7575: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7576: 
1.338     www      7577:     #
                   7578:     # Importing a rights file here
1.339     albertel 7579:     #
                   7580: 	    unless ($depthcount) {
1.599     albertel 7581: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7582: 		my $dir=$filename;
                   7583: 		$dir=~s|[^/]*$||;
                   7584: 		$location=&filelocation($dir,$location);
1.736     albertel 7585: 		my $rights_metadata =
                   7586: 		    &metadata($uri,'keys',$location,'_rights',
                   7587: 			      $depthcount+1);
                   7588: 		foreach my $rights (split(',',$rights_metadata)) {
                   7589: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7590: 		    $metathesekeys{$rights}=1;
1.339     albertel 7591: 		}
                   7592: 	    }
                   7593: 	}
1.737     albertel 7594: 	# uniqifiy package listing
                   7595: 	my %seen;
                   7596: 	my @uniq_packages =
                   7597: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7598: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7599: 
                   7600: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7601: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7602: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7603: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7604: # this is the end of "was not already recently cached
1.71      www      7605:     }
1.599     albertel 7606:     return $metaentry{':'.$what};
1.261     albertel 7607: }
                   7608: 
1.488     albertel 7609: sub metadata_create_package_def {
1.483     albertel 7610:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7611:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7612:     if ($subp eq 'default') { next; }
                   7613:     
1.599     albertel 7614:     if (defined($metaentry{':packages'})) {
                   7615: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7616:     } else {
1.599     albertel 7617: 	$metaentry{':packages'}=$package;
1.483     albertel 7618:     }
                   7619:     my $value=$packagetab{$key};
                   7620:     my $unikey;
                   7621:     $unikey='parameter_0_'.$name;
1.599     albertel 7622:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7623:     $$metathesekeys{$unikey}=1;
1.599     albertel 7624:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7625: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7626:     }
1.599     albertel 7627:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7628: 	$metaentry{':'.$unikey}=
                   7629: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7630:     }
                   7631: }
                   7632: 
1.261     albertel 7633: sub metadata_generate_part0 {
                   7634:     my ($metadata,$metacache,$uri) = @_;
                   7635:     my %allnames;
1.737     albertel 7636:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7637: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7638: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7639: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7640: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7641: 	    $allnames{$name}=$part;
                   7642: 	  }
                   7643: 	}
                   7644:     }
                   7645:     foreach my $name (keys(%allnames)) {
                   7646:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7647:       my $key=":parameter_0_$name";
1.261     albertel 7648:       $$metacache{"$key.part"}='0';
                   7649:       $$metacache{"$key.name"}=$name;
1.428     albertel 7650:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7651: 					   $allnames{$name}.'_'.$name.
                   7652: 					   '.type'};
1.428     albertel 7653:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7654: 			     '.display'};
1.644     www      7655:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7656:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7657:       $$metacache{"$key.display"}=$olddis;
                   7658:     }
1.71      www      7659: }
                   7660: 
1.764     albertel 7661: # ------------------------------------------------------ Devalidate title cache
                   7662: 
                   7663: sub devalidate_title_cache {
                   7664:     my ($url)=@_;
                   7665:     if (!$env{'request.course.id'}) { return; }
                   7666:     my $symb=&symbread($url);
                   7667:     if (!$symb) { return; }
                   7668:     my $key=$env{'request.course.id'}."\0".$symb;
                   7669:     &devalidate_cache_new('title',$key);
                   7670: }
                   7671: 
1.301     www      7672: # ------------------------------------------------- Get the title of a resource
                   7673: 
                   7674: sub gettitle {
                   7675:     my $urlsymb=shift;
                   7676:     my $symb=&symbread($urlsymb);
1.534     albertel 7677:     if ($symb) {
1.620     albertel 7678: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7679: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7680: 	if (defined($cached)) { 
                   7681: 	    return $result;
                   7682: 	}
1.534     albertel 7683: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7684: 	my $title='';
1.907     albertel 7685: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7686: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7687: 	} else {
                   7688: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7689: 		    &GDBM_READER(),0640)) {
                   7690: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7691: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7692: 		untie(%bighash);
                   7693: 	    }
1.534     albertel 7694: 	}
                   7695: 	$title=~s/\&colon\;/\:/gs;
                   7696: 	if ($title) {
1.599     albertel 7697: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7698: 	}
                   7699: 	$urlsymb=$url;
                   7700:     }
                   7701:     my $title=&metadata($urlsymb,'title');
                   7702:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7703:     return $title;
1.301     www      7704: }
1.613     albertel 7705: 
1.614     albertel 7706: sub get_slot {
                   7707:     my ($which,$cnum,$cdom)=@_;
                   7708:     if (!$cnum || !$cdom) {
1.790     albertel 7709: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7710: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7711: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7712:     }
1.703     albertel 7713:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7714:     my %slotinfo;
                   7715:     if (exists($remembered{$key})) {
                   7716: 	$slotinfo{$which} = $remembered{$key};
                   7717:     } else {
                   7718: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7719: 	&Apache::lonhomework::showhash(%slotinfo);
                   7720: 	my ($tmp)=keys(%slotinfo);
                   7721: 	if ($tmp=~/^error:/) { return (); }
                   7722: 	$remembered{$key} = $slotinfo{$which};
                   7723:     }
1.616     albertel 7724:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7725: 	return %{$slotinfo{$which}};
                   7726:     }
                   7727:     return $slotinfo{$which};
1.614     albertel 7728: }
1.31      www      7729: # ------------------------------------------------- Update symbolic store links
                   7730: 
                   7731: sub symblist {
                   7732:     my ($mapname,%newhash)=@_;
1.438     www      7733:     $mapname=&deversion(&declutter($mapname));
1.31      www      7734:     my %hash;
1.620     albertel 7735:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7736:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7737:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7738: 	    foreach my $url (keys %newhash) {
                   7739: 		next if ($url eq 'last_known'
                   7740: 			 && $env{'form.no_update_last_known'});
                   7741: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7742: 						    $newhash{$url}->[1],
                   7743: 						    $newhash{$url}->[0]);
1.191     harris41 7744:             }
1.31      www      7745:             if (untie(%hash)) {
                   7746: 		return 'ok';
                   7747:             }
                   7748:         }
                   7749:     }
                   7750:     return 'error';
1.212     www      7751: }
                   7752: 
                   7753: # --------------------------------------------------------------- Verify a symb
                   7754: 
                   7755: sub symbverify {
1.510     www      7756:     my ($symb,$thisurl)=@_;
                   7757:     my $thisfn=$thisurl;
1.439     www      7758:     $thisfn=&declutter($thisfn);
1.215     www      7759: # direct jump to resource in page or to a sequence - will construct own symbs
                   7760:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7761: # check URL part
1.409     www      7762:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7763: 
1.431     www      7764:     unless ($url eq $thisfn) { return 0; }
1.213     www      7765: 
1.216     www      7766:     $symb=&symbclean($symb);
1.510     www      7767:     $thisurl=&deversion($thisurl);
1.439     www      7768:     $thisfn=&deversion($thisfn);
1.213     www      7769: 
                   7770:     my %bighash;
                   7771:     my $okay=0;
1.431     www      7772: 
1.620     albertel 7773:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7774:                             &GDBM_READER(),0640)) {
1.510     www      7775:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7776:         unless ($ids) { 
1.510     www      7777:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7778:         }
                   7779:         if ($ids) {
                   7780: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7781: 	    foreach my $id (split(/\,/,$ids)) {
                   7782: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7783:                if (
                   7784:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7785:    eq $symb) { 
1.620     albertel 7786: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7787: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7788: 		       $okay=1; 
                   7789: 		   }
                   7790: 	       }
1.216     www      7791: 	   }
                   7792:         }
1.213     www      7793: 	untie(%bighash);
                   7794:     }
                   7795:     return $okay;
1.31      www      7796: }
                   7797: 
1.210     www      7798: # --------------------------------------------------------------- Clean-up symb
                   7799: 
                   7800: sub symbclean {
                   7801:     my $symb=shift;
1.568     albertel 7802:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7803: # remove version from map
                   7804:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7805: 
1.210     www      7806: # remove version from URL
                   7807:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7808: 
1.507     www      7809: # remove wrapper
                   7810: 
1.510     www      7811:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7812:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7813:     return $symb;
1.409     www      7814: }
                   7815: 
                   7816: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7817: 
                   7818: sub encode_symb {
                   7819:     my ($map,$resid,$url)=@_;
                   7820:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7821: }
1.409     www      7822: 
                   7823: sub decode_symb {
1.568     albertel 7824:     my $symb=shift;
                   7825:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7826:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7827:     return (&fixversion($map),$resid,&fixversion($url));
                   7828: }
                   7829: 
                   7830: sub fixversion {
                   7831:     my $fn=shift;
1.609     banghart 7832:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7833:     my %bighash;
                   7834:     my $uri=&clutter($fn);
1.620     albertel 7835:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7836: # is this cached?
1.599     albertel 7837:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7838:     if (defined($cached)) { return $result; }
                   7839: # unfortunately not cached, or expired
1.620     albertel 7840:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7841: 	    &GDBM_READER(),0640)) {
                   7842:  	if ($bighash{'version_'.$uri}) {
                   7843:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7844:  	    unless (($version eq 'mostrecent') || 
                   7845: 		    ($version==&getversion($uri))) {
1.440     www      7846:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7847:  	    }
                   7848:  	}
                   7849:  	untie %bighash;
1.413     www      7850:     }
1.599     albertel 7851:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7852: }
                   7853: 
                   7854: sub deversion {
                   7855:     my $url=shift;
                   7856:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7857:     return $url;
1.210     www      7858: }
                   7859: 
1.31      www      7860: # ------------------------------------------------------ Return symb list entry
                   7861: 
                   7862: sub symbread {
1.249     www      7863:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7864:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7865:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7866: # no filename provided? try from environment
1.44      www      7867:     unless ($thisfn) {
1.620     albertel 7868:         if ($env{'request.symb'}) {
                   7869: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7870: 	}
1.620     albertel 7871: 	$thisfn=$env{'request.filename'};
1.44      www      7872:     }
1.569     albertel 7873:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7874: # is that filename actually a symb? Verify, clean, and return
                   7875:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7876: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7877: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7878: 	}
1.242     www      7879:     }
1.44      www      7880:     $thisfn=declutter($thisfn);
1.31      www      7881:     my %hash;
1.37      www      7882:     my %bighash;
                   7883:     my $syval='';
1.620     albertel 7884:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7885:         my $targetfn = $thisfn;
1.609     banghart 7886:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7887:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7888:         }
1.687     albertel 7889: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7890: 	    $targetfn=$1;
                   7891: 	}
1.620     albertel 7892:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7893:                       &GDBM_READER(),0640)) {
1.481     raeburn  7894: 	    $syval=$hash{$targetfn};
1.37      www      7895:             untie(%hash);
                   7896:         }
                   7897: # ---------------------------------------------------------- There was an entry
                   7898:         if ($syval) {
1.601     albertel 7899: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7900: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7901: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7902: 		    #return $env{$cache_str}='';
1.601     albertel 7903: 		#}    
                   7904: 		#$syval.=$1;
                   7905: 	    #}
1.37      www      7906:         } else {
                   7907: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7908:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7909:                             &GDBM_READER(),0640)) {
1.37      www      7910: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7911:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7912:               unless ($ids) { 
                   7913:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7914:               }
                   7915:               unless ($ids) {
                   7916: # alias?
                   7917: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7918:               }
1.37      www      7919:               if ($ids) {
                   7920: # ------------------------------------------------------------------- Has ID(s)
                   7921:                  my @possibilities=split(/\,/,$ids);
1.39      www      7922:                  if ($#possibilities==0) {
                   7923: # ----------------------------------------------- There is only one possibility
1.37      www      7924: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7925: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7926: 						    $resid,$thisfn);
1.249     www      7927:                  } elsif (!$donotrecurse) {
1.39      www      7928: # ------------------------------------------ There is more than one possibility
                   7929:                      my $realpossible=0;
1.800     albertel 7930:                      foreach my $id (@possibilities) {
                   7931: 			 my $file=$bighash{'src_'.$id};
1.39      www      7932:                          if (&allowed('bre',$file)) {
1.800     albertel 7933:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7934:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7935: 				$realpossible++;
1.626     albertel 7936:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7937: 						    $resid,$thisfn);
1.39      www      7938:                             }
                   7939: 			 }
1.191     harris41 7940:                      }
1.39      www      7941: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7942:                  } else {
                   7943:                      $syval='';
1.37      www      7944:                  }
                   7945: 	      }
                   7946:               untie(%bighash)
1.481     raeburn  7947:            }
1.31      www      7948:         }
1.62      www      7949:         if ($syval) {
1.620     albertel 7950: 	    return $env{$cache_str}=$syval;
1.62      www      7951:         }
1.31      www      7952:     }
1.949     raeburn  7953:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7954:     return $env{$cache_str}='';
1.31      www      7955: }
                   7956: 
                   7957: # ---------------------------------------------------------- Return random seed
                   7958: 
1.32      www      7959: sub numval {
                   7960:     my $txt=shift;
                   7961:     $txt=~tr/A-J/0-9/;
                   7962:     $txt=~tr/a-j/0-9/;
                   7963:     $txt=~tr/K-T/0-9/;
                   7964:     $txt=~tr/k-t/0-9/;
                   7965:     $txt=~tr/U-Z/0-5/;
                   7966:     $txt=~tr/u-z/0-5/;
                   7967:     $txt=~s/\D//g;
1.564     albertel 7968:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7969:     return int($txt);
1.368     albertel 7970: }
                   7971: 
1.484     albertel 7972: sub numval2 {
                   7973:     my $txt=shift;
                   7974:     $txt=~tr/A-J/0-9/;
                   7975:     $txt=~tr/a-j/0-9/;
                   7976:     $txt=~tr/K-T/0-9/;
                   7977:     $txt=~tr/k-t/0-9/;
                   7978:     $txt=~tr/U-Z/0-5/;
                   7979:     $txt=~tr/u-z/0-5/;
                   7980:     $txt=~s/\D//g;
                   7981:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7982:     my $total;
                   7983:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7984:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7985:     return int($total);
                   7986: }
                   7987: 
1.575     albertel 7988: sub numval3 {
                   7989:     use integer;
                   7990:     my $txt=shift;
                   7991:     $txt=~tr/A-J/0-9/;
                   7992:     $txt=~tr/a-j/0-9/;
                   7993:     $txt=~tr/K-T/0-9/;
                   7994:     $txt=~tr/k-t/0-9/;
                   7995:     $txt=~tr/U-Z/0-5/;
                   7996:     $txt=~tr/u-z/0-5/;
                   7997:     $txt=~s/\D//g;
                   7998:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7999:     my $total;
                   8000:     foreach my $val (@txts) { $total+=$val; }
                   8001:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8002:     return $total;
                   8003: }
                   8004: 
1.675     albertel 8005: sub digest {
                   8006:     my ($data)=@_;
                   8007:     my $digest=&Digest::MD5::md5($data);
                   8008:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8009:     my ($e,$f);
                   8010:     {
                   8011:         use integer;
                   8012:         $e=($a+$b);
                   8013:         $f=($c+$d);
                   8014:         if ($_64bit) {
                   8015:             $e=(($e<<32)>>32);
                   8016:             $f=(($f<<32)>>32);
                   8017:         }
                   8018:     }
                   8019:     if (wantarray) {
                   8020: 	return ($e,$f);
                   8021:     } else {
                   8022: 	my $g;
                   8023: 	{
                   8024: 	    use integer;
                   8025: 	    $g=($e+$f);
                   8026: 	    if ($_64bit) {
                   8027: 		$g=(($g<<32)>>32);
                   8028: 	    }
                   8029: 	}
                   8030: 	return $g;
                   8031:     }
                   8032: }
                   8033: 
1.368     albertel 8034: sub latest_rnd_algorithm_id {
1.675     albertel 8035:     return '64bit5';
1.366     albertel 8036: }
1.32      www      8037: 
1.503     albertel 8038: sub get_rand_alg {
                   8039:     my ($courseid)=@_;
1.790     albertel 8040:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8041:     if ($courseid) {
1.620     albertel 8042: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8043:     }
                   8044:     return &latest_rnd_algorithm_id();
                   8045: }
                   8046: 
1.562     albertel 8047: sub validCODE {
                   8048:     my ($CODE)=@_;
                   8049:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8050:     return 0;
                   8051: }
                   8052: 
1.491     albertel 8053: sub getCODE {
1.620     albertel 8054:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8055:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8056: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8057: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8058: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8059:     }
                   8060:     return undef;
                   8061: }
                   8062: 
1.31      www      8063: sub rndseed {
1.155     albertel 8064:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8065:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8066:     if (!defined($symb)) {
1.366     albertel 8067: 	unless ($symb=$wsymb) { return time; }
                   8068:     }
                   8069:     if (!$courseid) { $courseid=$wcourseid; }
                   8070:     if (!$domain) { $domain=$wdomain; }
                   8071:     if (!$username) { $username=$wusername }
1.503     albertel 8072:     my $which=&get_rand_alg();
1.803     albertel 8073: 
1.491     albertel 8074:     if (defined(&getCODE())) {
1.675     albertel 8075: 	if ($which eq '64bit5') {
                   8076: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8077: 	} elsif ($which eq '64bit4') {
1.575     albertel 8078: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8079: 	} else {
                   8080: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8081: 	}
1.675     albertel 8082:     } elsif ($which eq '64bit5') {
                   8083: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8084:     } elsif ($which eq '64bit4') {
                   8085: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8086:     } elsif ($which eq '64bit3') {
                   8087: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8088:     } elsif ($which eq '64bit2') {
                   8089: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8090:     } elsif ($which eq '64bit') {
                   8091: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8092:     }
                   8093:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8094: }
                   8095: 
                   8096: sub rndseed_32bit {
                   8097:     my ($symb,$courseid,$domain,$username)=@_;
                   8098:     {
                   8099: 	use integer;
                   8100: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8101: 	my $symbseed=numval($symb) << 22;
                   8102: 	my $namechck=unpack("%32C*",$username) << 17;
                   8103: 	my $nameseed=numval($username) << 12;
                   8104: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8105: 	my $courseseed=unpack("%32C*",$courseid);
                   8106: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8107: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8108: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8109: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8110: 	return $num;
                   8111:     }
                   8112: }
                   8113: 
                   8114: sub rndseed_64bit {
                   8115:     my ($symb,$courseid,$domain,$username)=@_;
                   8116:     {
                   8117: 	use integer;
                   8118: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8119: 	my $symbseed=numval($symb) << 10;
                   8120: 	my $namechck=unpack("%32S*",$username);
                   8121: 	
                   8122: 	my $nameseed=numval($username) << 21;
                   8123: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8124: 	my $courseseed=unpack("%32S*",$courseid);
                   8125: 	
                   8126: 	my $num1=$symbchck+$symbseed+$namechck;
                   8127: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8129: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8130: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8131: 	return "$num1,$num2";
1.155     albertel 8132:     }
1.366     albertel 8133: }
                   8134: 
1.443     albertel 8135: sub rndseed_64bit2 {
                   8136:     my ($symb,$courseid,$domain,$username)=@_;
                   8137:     {
                   8138: 	use integer;
                   8139: 	# strings need to be an even # of cahracters long, it it is odd the
                   8140:         # last characters gets thrown away
                   8141: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8142: 	my $symbseed=numval($symb) << 10;
                   8143: 	my $namechck=unpack("%32S*",$username.' ');
                   8144: 	
                   8145: 	my $nameseed=numval($username) << 21;
1.501     albertel 8146: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8147: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8148: 	
                   8149: 	my $num1=$symbchck+$symbseed+$namechck;
                   8150: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8151: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8152: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8153: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8154: 	return "$num1,$num2";
                   8155:     }
                   8156: }
                   8157: 
                   8158: sub rndseed_64bit3 {
                   8159:     my ($symb,$courseid,$domain,$username)=@_;
                   8160:     {
                   8161: 	use integer;
                   8162: 	# strings need to be an even # of cahracters long, it it is odd the
                   8163:         # last characters gets thrown away
                   8164: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8165: 	my $symbseed=numval2($symb) << 10;
                   8166: 	my $namechck=unpack("%32S*",$username.' ');
                   8167: 	
                   8168: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8169: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8170: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8171: 	
                   8172: 	my $num1=$symbchck+$symbseed+$namechck;
                   8173: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8174: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8175: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8176: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8177: 	
1.503     albertel 8178: 	return "$num1:$num2";
1.443     albertel 8179:     }
                   8180: }
                   8181: 
1.575     albertel 8182: sub rndseed_64bit4 {
                   8183:     my ($symb,$courseid,$domain,$username)=@_;
                   8184:     {
                   8185: 	use integer;
                   8186: 	# strings need to be an even # of cahracters long, it it is odd the
                   8187:         # last characters gets thrown away
                   8188: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8189: 	my $symbseed=numval3($symb) << 10;
                   8190: 	my $namechck=unpack("%32S*",$username.' ');
                   8191: 	
                   8192: 	my $nameseed=numval3($username) << 21;
                   8193: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8194: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8195: 	
                   8196: 	my $num1=$symbchck+$symbseed+$namechck;
                   8197: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8198: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8199: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8200: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8201: 	
                   8202: 	return "$num1:$num2";
                   8203:     }
                   8204: }
                   8205: 
1.675     albertel 8206: sub rndseed_64bit5 {
                   8207:     my ($symb,$courseid,$domain,$username)=@_;
                   8208:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8209:     return "$num1:$num2";
                   8210: }
                   8211: 
1.366     albertel 8212: sub rndseed_CODE_64bit {
                   8213:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8214:     {
1.366     albertel 8215: 	use integer;
1.443     albertel 8216: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8217: 	my $symbseed=numval2($symb);
1.491     albertel 8218: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8219: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8220: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8221: 	my $num1=$symbseed+$CODEchck;
                   8222: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8223: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8224: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8225: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8226: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8227: 	return "$num1:$num2";
1.366     albertel 8228:     }
                   8229: }
                   8230: 
1.575     albertel 8231: sub rndseed_CODE_64bit4 {
                   8232:     my ($symb,$courseid,$domain,$username)=@_;
                   8233:     {
                   8234: 	use integer;
                   8235: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8236: 	my $symbseed=numval3($symb);
                   8237: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8238: 	my $CODEseed=numval3(&getCODE());
                   8239: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8240: 	my $num1=$symbseed+$CODEchck;
                   8241: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8242: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8243: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8244: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8245: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8246: 	return "$num1:$num2";
                   8247:     }
                   8248: }
                   8249: 
1.675     albertel 8250: sub rndseed_CODE_64bit5 {
                   8251:     my ($symb,$courseid,$domain,$username)=@_;
                   8252:     my $code = &getCODE();
                   8253:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8254:     return "$num1:$num2";
                   8255: }
                   8256: 
1.366     albertel 8257: sub setup_random_from_rndseed {
                   8258:     my ($rndseed)=@_;
1.503     albertel 8259:     if ($rndseed =~/([,:])/) {
                   8260: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8261: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8262:     } else {
                   8263: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8264:     }
1.36      albertel 8265: }
                   8266: 
1.474     albertel 8267: sub latest_receipt_algorithm_id {
1.835     albertel 8268:     return 'receipt3';
1.474     albertel 8269: }
                   8270: 
1.480     www      8271: sub recunique {
                   8272:     my $fucourseid=shift;
                   8273:     my $unique;
1.835     albertel 8274:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8275: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8276: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8277:     } else {
                   8278: 	$unique=$perlvar{'lonReceipt'};
                   8279:     }
                   8280:     return unpack("%32C*",$unique);
                   8281: }
                   8282: 
                   8283: sub recprefix {
                   8284:     my $fucourseid=shift;
                   8285:     my $prefix;
1.835     albertel 8286:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8287: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8288: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8289:     } else {
                   8290: 	$prefix=$perlvar{'lonHostID'};
                   8291:     }
                   8292:     return unpack("%32C*",$prefix);
                   8293: }
                   8294: 
1.76      www      8295: sub ireceipt {
1.474     albertel 8296:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8297: 
                   8298:     my $return =&recprefix($fucourseid).'-';
                   8299: 
                   8300:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8301: 	$env{'request.state'} eq 'construct') {
                   8302: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8303: 	return $return;
                   8304:     }
                   8305: 
1.76      www      8306:     my $cuname=unpack("%32C*",$funame);
                   8307:     my $cudom=unpack("%32C*",$fudom);
                   8308:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8309:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8310:     my $cunique=&recunique($fucourseid);
1.474     albertel 8311:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8312:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8313: 
1.790     albertel 8314: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8315: 			       
                   8316: 	$return.= ($cunique%$cuname+
                   8317: 		   $cunique%$cudom+
                   8318: 		   $cusymb%$cuname+
                   8319: 		   $cusymb%$cudom+
                   8320: 		   $cucourseid%$cuname+
                   8321: 		   $cucourseid%$cudom+
                   8322: 		   $cpart%$cuname+
                   8323: 		   $cpart%$cudom);
                   8324:     } else {
                   8325: 	$return.= ($cunique%$cuname+
                   8326: 		   $cunique%$cudom+
                   8327: 		   $cusymb%$cuname+
                   8328: 		   $cusymb%$cudom+
                   8329: 		   $cucourseid%$cuname+
                   8330: 		   $cucourseid%$cudom);
                   8331:     }
                   8332:     return $return;
1.76      www      8333: }
                   8334: 
                   8335: sub receipt {
1.474     albertel 8336:     my ($part)=@_;
1.790     albertel 8337:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8338:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8339: }
1.260     ng       8340: 
1.790     albertel 8341: sub whichuser {
                   8342:     my ($passedsymb)=@_;
                   8343:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8344:     if (defined($env{'form.grade_symb'})) {
                   8345: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8346: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8347: 	if (!$allowed &&
                   8348: 	    exists($env{'request.course.sec'}) &&
                   8349: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8350: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8351: 			      '/'.$env{'request.course.sec'});
                   8352: 	}
                   8353: 	if ($allowed) {
                   8354: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8355: 	    $courseid=$tmp_courseid;
                   8356: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8357: 	    ($name)=&get_env_multiple('form.grade_username');
                   8358: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8359: 	}
                   8360:     }
                   8361:     if (!$passedsymb) {
                   8362: 	$symb=&symbread();
                   8363:     } else {
                   8364: 	$symb=$passedsymb;
                   8365:     }
                   8366:     $courseid=$env{'request.course.id'};
                   8367:     $domain=$env{'user.domain'};
                   8368:     $name=$env{'user.name'};
                   8369:     if ($name eq 'public' && $domain eq 'public') {
                   8370: 	if (!defined($env{'form.username'})) {
                   8371: 	    $env{'form.username'}.=time.rand(10000000);
                   8372: 	}
                   8373: 	$name.=$env{'form.username'};
                   8374:     }
                   8375:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8376: 
                   8377: }
                   8378: 
1.36      albertel 8379: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8380: # returns either the contents of the file or 
                   8381: # -1 if the file doesn't exist
1.481     raeburn  8382: #
                   8383: # if the target is a file that was uploaded via DOCS, 
                   8384: # a check will be made to see if a current copy exists on the local server,
                   8385: # if it does this will be served, otherwise a copy will be retrieved from
                   8386: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8387: # the local server.   
1.472     albertel 8388: 
1.36      albertel 8389: sub getfile {
1.538     albertel 8390:     my ($file) = @_;
1.609     banghart 8391:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8392:     &repcopy($file);
                   8393:     return &readfile($file);
                   8394: }
                   8395: 
                   8396: sub repcopy_userfile {
                   8397:     my ($file)=@_;
1.609     banghart 8398:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8399:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8400:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8401: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8402:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8403:     if (-e "$file") {
1.828     www      8404: # we already have a local copy, check it out
1.538     albertel 8405: 	my @fileinfo = stat($file);
1.828     www      8406: 	my $rtncode;
                   8407: 	my $info;
1.538     albertel 8408: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8409: 	if ($lwpresp ne 'ok') {
1.828     www      8410: # there is no such file anymore, even though we had a local copy
1.482     albertel 8411: 	    if ($rtncode eq '404') {
1.538     albertel 8412: 		unlink($file);
1.482     albertel 8413: 	    }
                   8414: 	    return -1;
                   8415: 	}
                   8416: 	if ($info < $fileinfo[9]) {
1.828     www      8417: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8418: 	    return 'ok';
1.828     www      8419: 	} else {
                   8420: # the file is outdated, get rid of it
                   8421: 	    unlink($file);
1.482     albertel 8422: 	}
1.828     www      8423:     }
                   8424: # one way or the other, at this point, we don't have the file
                   8425: # construct the correct path for the file
                   8426:     my @parts = ($cdom,$cnum); 
                   8427:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8428: 	push @parts, split(/\//,$1);
                   8429:     }
                   8430:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8431:     foreach my $part (@parts) {
                   8432: 	$path .= '/'.$part;
                   8433: 	if (!-e $path) {
                   8434: 	    mkdir($path,0770);
1.482     albertel 8435: 	}
                   8436:     }
1.828     www      8437: # now the path exists for sure
                   8438: # get a user agent
                   8439:     my $ua=new LWP::UserAgent;
                   8440:     my $transferfile=$file.'.in.transfer';
                   8441: # FIXME: this should flock
                   8442:     if (-e $transferfile) { return 'ok'; }
                   8443:     my $request;
                   8444:     $uri=~s/^\///;
1.980     raeburn  8445:     my $homeserver = &homeserver($cnum,$cdom);
                   8446:     my $protocol = $protocol{$homeserver};
                   8447:     $protocol = 'http' if ($protocol ne 'https');
                   8448:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8449:     my $response=$ua->request($request,$transferfile);
                   8450: # did it work?
                   8451:     if ($response->is_error()) {
                   8452: 	unlink($transferfile);
                   8453: 	&logthis("Userfile repcopy failed for $uri");
                   8454: 	return -1;
                   8455:     }
                   8456: # worked, rename the transfer file
                   8457:     rename($transferfile,$file);
1.607     raeburn  8458:     return 'ok';
1.481     raeburn  8459: }
                   8460: 
1.517     albertel 8461: sub tokenwrapper {
                   8462:     my $uri=shift;
1.980     raeburn  8463:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8464:     $uri=~s|^/||;
1.620     albertel 8465:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8466:     my $token=$1;
1.552     albertel 8467:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8468:     if ($udom && $uname && $file) {
                   8469: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8470:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8471:         my $homeserver = &homeserver($uname,$udom);
                   8472:         my $protocol = $protocol{$homeserver};
                   8473:         $protocol = 'http' if ($protocol ne 'https');
                   8474:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8475:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8476:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8477:     } else {
                   8478:         return '/adm/notfound.html';
                   8479:     }
                   8480: }
                   8481: 
1.828     www      8482: # call with reqtype HEAD: get last modification time
                   8483: # call with reqtype GET: get the file contents
                   8484: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8485: #
1.481     raeburn  8486: sub getuploaded {
                   8487:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8488:     $uri=~s/^\///;
1.980     raeburn  8489:     my $homeserver = &homeserver($cnum,$cdom);
                   8490:     my $protocol = $protocol{$homeserver};
                   8491:     $protocol = 'http' if ($protocol ne 'https');
                   8492:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8493:     my $ua=new LWP::UserAgent;
                   8494:     my $request=new HTTP::Request($reqtype,$uri);
                   8495:     my $response=$ua->request($request);
                   8496:     $$rtncode = $response->code;
1.482     albertel 8497:     if (! $response->is_success()) {
                   8498: 	return 'failed';
                   8499:     }      
                   8500:     if ($reqtype eq 'HEAD') {
1.486     www      8501: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8502:     } elsif ($reqtype eq 'GET') {
                   8503: 	$$info = $response->content;
1.472     albertel 8504:     }
1.482     albertel 8505:     return 'ok';
1.36      albertel 8506: }
                   8507: 
1.481     raeburn  8508: sub readfile {
                   8509:     my $file = shift;
                   8510:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8511:     my $fh;
                   8512:     open($fh,"<$file");
                   8513:     my $a='';
1.800     albertel 8514:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8515:     return $a;
                   8516: }
                   8517: 
1.36      albertel 8518: sub filelocation {
1.590     banghart 8519:     my ($dir,$file) = @_;
                   8520:     my $location;
                   8521:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8522: 
                   8523:     if ($file =~ m-^/adm/-) {
                   8524: 	$file=~s-^/adm/wrapper/-/-;
                   8525: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8526:     }
1.882     albertel 8527: 
1.590     banghart 8528:     if ($file=~m:^/~:) { # is a contruction space reference
                   8529:         $location = $file;
                   8530:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8531:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8532: 	# is a correct contruction space reference
                   8533:         $location = $file;
1.956     raeburn  8534:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8535:         $location = $file;
1.609     banghart 8536:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8537:         my ($udom,$uname,$filename)=
1.811     albertel 8538:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8539:         my $home=&homeserver($uname,$udom);
                   8540:         my $is_me=0;
                   8541:         my @ids=&current_machine_ids();
                   8542:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8543:         if ($is_me) {
1.955     raeburn  8544:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8545:         } else {
                   8546:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8547:   	      $udom.'/'.$uname.'/'.$filename;
                   8548:         }
1.882     albertel 8549:     } elsif ($file =~ m-^/adm/-) {
                   8550: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8551:     } else {
                   8552:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8553:         $file=~s:^/res/:/:;
                   8554:         if ( !( $file =~ m:^/:) ) {
                   8555:             $location = $dir. '/'.$file;
                   8556:         } else {
                   8557:             $location = '/home/httpd/html/res'.$file;
                   8558:         }
1.59      albertel 8559:     }
1.590     banghart 8560:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8561:     while ($location=~m{/\.\./}) {
                   8562: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8563: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8564: 	} else {
                   8565: 	    $location=~ s{/\.\./}{/}g;
                   8566: 	}
                   8567:     } #remove dir/..
1.590     banghart 8568:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8569:     return $location;
1.46      www      8570: }
1.36      albertel 8571: 
1.46      www      8572: sub hreflocation {
                   8573:     my ($dir,$file)=@_;
1.980     raeburn  8574:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8575: 	$file=filelocation($dir,$file);
1.700     albertel 8576:     } elsif ($file=~m-^/adm/-) {
                   8577: 	$file=~s-^/adm/wrapper/-/-;
                   8578: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8579:     }
                   8580:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8581: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8582:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8583: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8584:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8585: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8586: 	    -/uploaded/$1/$2/-x;
1.46      www      8587:     }
1.913     albertel 8588:     if ($file=~ m{^/userfiles/}) {
                   8589: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8590:     }
1.462     albertel 8591:     return $file;
1.465     albertel 8592: }
                   8593: 
                   8594: sub current_machine_domains {
1.853     albertel 8595:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8596: }
                   8597: 
                   8598: sub machine_domains {
                   8599:     my ($hostname) = @_;
1.465     albertel 8600:     my @domains;
1.838     albertel 8601:     my %hostname = &all_hostnames();
1.465     albertel 8602:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8603: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8604: 	if ($hostname eq $name) {
1.844     albertel 8605: 	    push(@domains,&host_domain($id));
1.465     albertel 8606: 	}
                   8607:     }
                   8608:     return @domains;
                   8609: }
                   8610: 
                   8611: sub current_machine_ids {
1.853     albertel 8612:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8613: }
                   8614: 
                   8615: sub machine_ids {
                   8616:     my ($hostname) = @_;
                   8617:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8618:     my @ids;
1.888     albertel 8619:     my %name_to_host = &all_names();
1.889     albertel 8620:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8621: 	return @{ $name_to_host{$hostname} };
                   8622:     }
                   8623:     return;
1.31      www      8624: }
                   8625: 
1.824     raeburn  8626: sub additional_machine_domains {
                   8627:     my @domains;
                   8628:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8629:     while( my $line = <$fh>) {
                   8630:         $line =~ s/\s//g;
                   8631:         push(@domains,$line);
                   8632:     }
                   8633:     return @domains;
                   8634: }
                   8635: 
                   8636: sub default_login_domain {
                   8637:     my $domain = $perlvar{'lonDefDomain'};
                   8638:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8639:     foreach my $posdom (&current_machine_domains(),
                   8640:                         &additional_machine_domains()) {
                   8641:         if (lc($posdom) eq lc($testdomain)) {
                   8642:             $domain=$posdom;
                   8643:             last;
                   8644:         }
                   8645:     }
                   8646:     return $domain;
                   8647: }
                   8648: 
1.31      www      8649: # ------------------------------------------------------------- Declutters URLs
                   8650: 
                   8651: sub declutter {
                   8652:     my $thisfn=shift;
1.569     albertel 8653:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8654:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8655:     $thisfn=~s/^\///;
1.697     albertel 8656:     $thisfn=~s|^adm/wrapper/||;
                   8657:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8658:     $thisfn=~s/^res\///;
1.235     www      8659:     $thisfn=~s/\?.+$//;
1.268     www      8660:     return $thisfn;
                   8661: }
                   8662: 
                   8663: # ------------------------------------------------------------- Clutter up URLs
                   8664: 
                   8665: sub clutter {
                   8666:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8667:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8668: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8669:        $thisfn='/res'.$thisfn; 
                   8670:     }
1.694     albertel 8671:     if ($thisfn !~m|/adm|) {
1.695     albertel 8672: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8673: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8674: 	} else {
                   8675: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8676: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8677: 	    if ($embstyle eq 'ssi'
                   8678: 		|| ($embstyle eq 'hdn')
                   8679: 		|| ($embstyle eq 'rat')
                   8680: 		|| ($embstyle eq 'prv')
                   8681: 		|| ($embstyle eq 'ign')) {
                   8682: 		#do nothing with these
                   8683: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8684: 		|| ($embstyle eq 'emb')
                   8685: 		|| ($embstyle eq 'wrp')) {
                   8686: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8687: 	    } elsif ($embstyle eq 'unk'
                   8688: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8689: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8690: 	    } else {
1.718     www      8691: #		&logthis("Got a blank emb style");
1.695     albertel 8692: 	    }
1.694     albertel 8693: 	}
                   8694:     }
1.31      www      8695:     return $thisfn;
1.12      www      8696: }
                   8697: 
1.787     albertel 8698: sub clutter_with_no_wrapper {
                   8699:     my $uri = &clutter(shift);
                   8700:     if ($uri =~ m-^/adm/-) {
                   8701: 	$uri =~ s-^/adm/wrapper/-/-;
                   8702: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8703:     }
                   8704:     return $uri;
                   8705: }
                   8706: 
1.557     albertel 8707: sub freeze_escape {
                   8708:     my ($value)=@_;
                   8709:     if (ref($value)) {
                   8710: 	$value=&nfreeze($value);
                   8711: 	return '__FROZEN__'.&escape($value);
                   8712:     }
                   8713:     return &escape($value);
                   8714: }
                   8715: 
1.11      www      8716: 
1.557     albertel 8717: sub thaw_unescape {
                   8718:     my ($value)=@_;
                   8719:     if ($value =~ /^__FROZEN__/) {
                   8720: 	substr($value,0,10,undef);
                   8721: 	$value=&unescape($value);
                   8722: 	return &thaw($value);
                   8723:     }
                   8724:     return &unescape($value);
                   8725: }
                   8726: 
1.436     albertel 8727: sub correct_line_ends {
                   8728:     my ($result)=@_;
                   8729:     $$result =~s/\r\n/\n/mg;
                   8730:     $$result =~s/\r/\n/mg;
1.415     albertel 8731: }
1.1       albertel 8732: # ================================================================ Main Program
                   8733: 
1.184     www      8734: sub goodbye {
1.204     albertel 8735:    &logthis("Starting Shut down");
1.443     albertel 8736: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8737:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8738: #converted
1.599     albertel 8739: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8740:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8741: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8742: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8743: #1.1 only
1.870     albertel 8744: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8745: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8746: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8747: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8748:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8749:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8750:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8751:    &flushcourselogs();
                   8752:    &logthis("Shutting down");
                   8753: }
                   8754: 
1.852     albertel 8755: sub get_dns {
1.869     albertel 8756:     my ($url,$func,$ignore_cache) = @_;
                   8757:     if (!$ignore_cache) {
                   8758: 	my ($content,$cached)=
                   8759: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8760: 	if ($cached) {
                   8761: 	    &$func($content);
                   8762: 	    return;
                   8763: 	}
                   8764:     }
                   8765: 
                   8766:     my %alldns;
1.852     albertel 8767:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8768:     foreach my $dns (<$config>) {
                   8769: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  8770:         my $line = $1;
                   8771:         my ($host,$protocol) = split(/:/,$line);
                   8772:         if ($protocol ne 'https') {
                   8773:             $protocol = 'http';
                   8774:         }
                   8775: 	$alldns{$host} = $protocol;
1.869     albertel 8776:     }
                   8777:     while (%alldns) {
                   8778: 	my ($dns) = keys(%alldns);
1.852     albertel 8779: 	my $ua=new LWP::UserAgent;
1.979     raeburn  8780: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8781: 	my $response=$ua->request($request);
1.979     raeburn  8782:         delete($alldns{$dns});
1.852     albertel 8783: 	next if ($response->is_error());
                   8784: 	my @content = split("\n",$response->content);
1.869     albertel 8785: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8786: 	&$func(\@content);
1.869     albertel 8787: 	return;
1.852     albertel 8788:     }
                   8789:     close($config);
1.871     albertel 8790:     my $which = (split('/',$url))[3];
                   8791:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8792:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8793:     my @content = <$config>;
                   8794:     &$func(\@content);
                   8795:     return;
1.852     albertel 8796: }
1.327     albertel 8797: # ------------------------------------------------------------ Read domain file
                   8798: {
1.852     albertel 8799:     my $loaded;
1.846     albertel 8800:     my %domain;
                   8801: 
1.852     albertel 8802:     sub parse_domain_tab {
                   8803: 	my ($lines) = @_;
                   8804: 	foreach my $line (@$lines) {
                   8805: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8806: 
1.846     albertel 8807: 	    chomp($line);
1.852     albertel 8808: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8809: 	    my %this_domain;
                   8810: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8811: 			       'lang_def', 'city', 'longi', 'lati',
                   8812: 			       'primary') {
                   8813: 		$this_domain{$field} = shift(@elements);
                   8814: 	    }
                   8815: 	    $domain{$name} = \%this_domain;
1.852     albertel 8816: 	}
                   8817:     }
1.864     albertel 8818: 
                   8819:     sub reset_domain_info {
                   8820: 	undef($loaded);
                   8821: 	undef(%domain);
                   8822:     }
                   8823: 
1.852     albertel 8824:     sub load_domain_tab {
1.869     albertel 8825: 	my ($ignore_cache) = @_;
                   8826: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8827: 	my $fh;
                   8828: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8829: 	    my @lines = <$fh>;
                   8830: 	    &parse_domain_tab(\@lines);
1.448     albertel 8831: 	}
1.852     albertel 8832: 	close($fh);
                   8833: 	$loaded = 1;
1.327     albertel 8834:     }
1.846     albertel 8835: 
                   8836:     sub domain {
1.852     albertel 8837: 	&load_domain_tab() if (!$loaded);
                   8838: 
1.846     albertel 8839: 	my ($name,$what) = @_;
                   8840: 	return if ( !exists($domain{$name}) );
                   8841: 
                   8842: 	if (!$what) {
                   8843: 	    return $domain{$name}{'description'};
                   8844: 	}
                   8845: 	return $domain{$name}{$what};
                   8846:     }
1.974     raeburn  8847: 
                   8848:     sub domain_info {
                   8849:         &load_domain_tab() if (!$loaded);
                   8850:         return %domain;
                   8851:     }
                   8852: 
1.327     albertel 8853: }
                   8854: 
                   8855: 
1.1       albertel 8856: # ------------------------------------------------------------- Read hosts file
                   8857: {
1.838     albertel 8858:     my %hostname;
1.844     albertel 8859:     my %hostdom;
1.845     albertel 8860:     my %libserv;
1.852     albertel 8861:     my $loaded;
1.888     albertel 8862:     my %name_to_host;
1.852     albertel 8863: 
                   8864:     sub parse_hosts_tab {
                   8865: 	my ($file) = @_;
                   8866: 	foreach my $configline (@$file) {
                   8867: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8868: 	    next if ($configline =~ /^\^/);
                   8869: 	    chomp($configline);
1.968     raeburn  8870: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8871: 	    $name=~s/\s//g;
                   8872: 	    if ($id && $domain && $role && $name) {
                   8873: 		$hostname{$id}=$name;
1.888     albertel 8874: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8875: 		$hostdom{$id}=$domain;
                   8876: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8877:                 if (defined($protocol)) {
                   8878:                     if ($protocol eq 'https') {
                   8879:                         $protocol{$id} = $protocol;
                   8880:                     } else {
                   8881:                         $protocol{$id} = 'http'; 
                   8882:                     }
1.968     raeburn  8883:                 } else {
1.969     raeburn  8884:                     $protocol{$id} = 'http';
1.968     raeburn  8885:                 }
1.852     albertel 8886: 	    }
                   8887: 	}
                   8888:     }
1.864     albertel 8889:     
                   8890:     sub reset_hosts_info {
1.897     albertel 8891: 	&purge_remembered();
1.864     albertel 8892: 	&reset_domain_info();
                   8893: 	&reset_hosts_ip_info();
1.892     albertel 8894: 	undef(%name_to_host);
1.864     albertel 8895: 	undef(%hostname);
                   8896: 	undef(%hostdom);
                   8897: 	undef(%libserv);
                   8898: 	undef($loaded);
                   8899:     }
1.1       albertel 8900: 
1.852     albertel 8901:     sub load_hosts_tab {
1.869     albertel 8902: 	my ($ignore_cache) = @_;
                   8903: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8904: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8905: 	my @config = <$config>;
                   8906: 	&parse_hosts_tab(\@config);
                   8907: 	close($config);
                   8908: 	$loaded=1;
1.1       albertel 8909:     }
1.852     albertel 8910: 
1.838     albertel 8911:     sub hostname {
1.852     albertel 8912: 	&load_hosts_tab() if (!$loaded);
                   8913: 
1.838     albertel 8914: 	my ($lonid) = @_;
                   8915: 	return $hostname{$lonid};
                   8916:     }
1.845     albertel 8917: 
1.838     albertel 8918:     sub all_hostnames {
1.852     albertel 8919: 	&load_hosts_tab() if (!$loaded);
                   8920: 
1.838     albertel 8921: 	return %hostname;
                   8922:     }
1.845     albertel 8923: 
1.888     albertel 8924:     sub all_names {
                   8925: 	&load_hosts_tab() if (!$loaded);
                   8926: 
                   8927: 	return %name_to_host;
                   8928:     }
                   8929: 
1.974     raeburn  8930:     sub all_host_domain {
                   8931:         &load_hosts_tab() if (!$loaded);
                   8932:         return %hostdom;
                   8933:     }
                   8934: 
1.845     albertel 8935:     sub is_library {
1.852     albertel 8936: 	&load_hosts_tab() if (!$loaded);
                   8937: 
1.845     albertel 8938: 	return exists($libserv{$_[0]});
                   8939:     }
                   8940: 
                   8941:     sub all_library {
1.852     albertel 8942: 	&load_hosts_tab() if (!$loaded);
                   8943: 
1.845     albertel 8944: 	return %libserv;
                   8945:     }
                   8946: 
1.841     albertel 8947:     sub get_servers {
1.852     albertel 8948: 	&load_hosts_tab() if (!$loaded);
                   8949: 
1.841     albertel 8950: 	my ($domain,$type) = @_;
                   8951: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8952: 	                                          : %hostname;
                   8953: 	my %result;
1.842     albertel 8954: 	if (ref($domain) eq 'ARRAY') {
                   8955: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8956: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8957: 		    $result{$host} = $hostname;
                   8958: 		}
                   8959: 	    }
                   8960: 	} else {
                   8961: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8962: 		if ($hostdom{$host} eq $domain) {
                   8963: 		    $result{$host} = $hostname;
                   8964: 		}
1.841     albertel 8965: 	    }
                   8966: 	}
                   8967: 	return %result;
                   8968:     }
1.845     albertel 8969: 
1.844     albertel 8970:     sub host_domain {
1.852     albertel 8971: 	&load_hosts_tab() if (!$loaded);
                   8972: 
1.844     albertel 8973: 	my ($lonid) = @_;
                   8974: 	return $hostdom{$lonid};
                   8975:     }
                   8976: 
1.841     albertel 8977:     sub all_domains {
1.852     albertel 8978: 	&load_hosts_tab() if (!$loaded);
                   8979: 
1.841     albertel 8980: 	my %seen;
                   8981: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8982: 	return @uniq;
                   8983:     }
1.1       albertel 8984: }
                   8985: 
1.847     albertel 8986: { 
                   8987:     my %iphost;
1.856     albertel 8988:     my %name_to_ip;
                   8989:     my %lonid_to_ip;
1.869     albertel 8990: 
1.847     albertel 8991:     sub get_hosts_from_ip {
                   8992: 	my ($ip) = @_;
                   8993: 	my %iphosts = &get_iphost();
                   8994: 	if (ref($iphosts{$ip})) {
                   8995: 	    return @{$iphosts{$ip}};
                   8996: 	}
                   8997: 	return;
1.839     albertel 8998:     }
1.864     albertel 8999:     
                   9000:     sub reset_hosts_ip_info {
                   9001: 	undef(%iphost);
                   9002: 	undef(%name_to_ip);
                   9003: 	undef(%lonid_to_ip);
                   9004:     }
1.856     albertel 9005: 
                   9006:     sub get_host_ip {
                   9007: 	my ($lonid) = @_;
                   9008: 	if (exists($lonid_to_ip{$lonid})) {
                   9009: 	    return $lonid_to_ip{$lonid};
                   9010: 	}
                   9011: 	my $name=&hostname($lonid);
                   9012:    	my $ip = gethostbyname($name);
                   9013: 	return if (!$ip || length($ip) ne 4);
                   9014: 	$ip=inet_ntoa($ip);
                   9015: 	$name_to_ip{$name}   = $ip;
                   9016: 	$lonid_to_ip{$lonid} = $ip;
                   9017: 	return $ip;
                   9018:     }
1.847     albertel 9019:     
                   9020:     sub get_iphost {
1.869     albertel 9021: 	my ($ignore_cache) = @_;
1.894     albertel 9022: 
1.869     albertel 9023: 	if (!$ignore_cache) {
                   9024: 	    if (%iphost) {
                   9025: 		return %iphost;
                   9026: 	    }
                   9027: 	    my ($ip_info,$cached)=
                   9028: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9029: 	    if ($cached) {
                   9030: 		%iphost      = %{$ip_info->[0]};
                   9031: 		%name_to_ip  = %{$ip_info->[1]};
                   9032: 		%lonid_to_ip = %{$ip_info->[2]};
                   9033: 		return %iphost;
                   9034: 	    }
                   9035: 	}
1.894     albertel 9036: 
                   9037: 	# get yesterday's info for fallback
                   9038: 	my %old_name_to_ip;
                   9039: 	my ($ip_info,$cached)=
                   9040: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9041: 	if ($cached) {
                   9042: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9043: 	}
                   9044: 
1.888     albertel 9045: 	my %name_to_host = &all_names();
                   9046: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9047: 	    my $ip;
                   9048: 	    if (!exists($name_to_ip{$name})) {
                   9049: 		$ip = gethostbyname($name);
                   9050: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9051: 		    if (defined($old_name_to_ip{$name})) {
                   9052: 			$ip = $old_name_to_ip{$name};
                   9053: 			&logthis("Can't find $name defaulting to old $ip");
                   9054: 		    } else {
                   9055: 			&logthis("Name $name no IP found");
                   9056: 			next;
                   9057: 		    }
                   9058: 		} else {
                   9059: 		    $ip=inet_ntoa($ip);
1.847     albertel 9060: 		}
                   9061: 		$name_to_ip{$name} = $ip;
                   9062: 	    } else {
                   9063: 		$ip = $name_to_ip{$name};
1.653     albertel 9064: 	    }
1.888     albertel 9065: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9066: 		$lonid_to_ip{$id} = $ip;
                   9067: 	    }
                   9068: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9069: 	}
1.869     albertel 9070: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9071: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9072: 				      48*60*60);
1.869     albertel 9073: 
1.847     albertel 9074: 	return %iphost;
1.598     albertel 9075:     }
                   9076: 
1.992     raeburn  9077:     #
                   9078:     #  Given a DNS returns the loncapa host name for that DNS 
                   9079:     # 
                   9080:     sub host_from_dns {
                   9081:         my ($dns) = @_;
                   9082:         my @hosts;
                   9083:         my $ip;
                   9084: 
1.993   ! raeburn  9085:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9086:             $ip = $name_to_ip{$dns};
                   9087:         }
                   9088:         if (!$ip) {
                   9089:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9090:             if (length($ip) == 4) { 
                   9091: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9092:             }
                   9093:         }
                   9094:         if ($ip) {
                   9095: 	    @hosts = get_hosts_from_ip($ip);
                   9096: 	    return $hosts[0];
                   9097:         }
                   9098:         return undef;
1.986     foxr     9099:     }
1.992     raeburn  9100: 
1.986     foxr     9101: }
                   9102: 
1.862     albertel 9103: BEGIN {
                   9104: 
                   9105: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9106:     unless ($readit) {
                   9107: {
                   9108:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9109:     %perlvar = (%perlvar,%{$configvars});
                   9110: }
                   9111: 
                   9112: 
1.1       albertel 9113: # ------------------------------------------------------ Read spare server file
                   9114: {
1.448     albertel 9115:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9116: 
                   9117:     while (my $configline=<$config>) {
                   9118:        chomp($configline);
1.284     matthew  9119:        if ($configline) {
1.784     albertel 9120: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9121: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9122: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9123:        }
                   9124:     }
1.448     albertel 9125:     close($config);
1.1       albertel 9126: }
1.11      www      9127: # ------------------------------------------------------------ Read permissions
                   9128: {
1.448     albertel 9129:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9130: 
                   9131:     while (my $configline=<$config>) {
1.448     albertel 9132: 	chomp($configline);
                   9133: 	if ($configline) {
                   9134: 	    my ($role,$perm)=split(/ /,$configline);
                   9135: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9136: 	}
1.11      www      9137:     }
1.448     albertel 9138:     close($config);
1.11      www      9139: }
                   9140: 
                   9141: # -------------------------------------------- Read plain texts for permissions
                   9142: {
1.448     albertel 9143:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9144: 
                   9145:     while (my $configline=<$config>) {
1.448     albertel 9146: 	chomp($configline);
                   9147: 	if ($configline) {
1.742     raeburn  9148: 	    my ($short,@plain)=split(/:/,$configline);
                   9149:             %{$prp{$short}} = ();
                   9150: 	    if (@plain > 0) {
                   9151:                 $prp{$short}{'std'} = $plain[0];
                   9152:                 for (my $i=1; $i<@plain; $i++) {
                   9153:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9154:                 }
                   9155:             }
1.448     albertel 9156: 	}
1.135     www      9157:     }
1.448     albertel 9158:     close($config);
1.135     www      9159: }
                   9160: 
                   9161: # ---------------------------------------------------------- Read package table
                   9162: {
1.448     albertel 9163:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9164: 
                   9165:     while (my $configline=<$config>) {
1.483     albertel 9166: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9167: 	chomp($configline);
                   9168: 	my ($short,$plain)=split(/:/,$configline);
                   9169: 	my ($pack,$name)=split(/\&/,$short);
                   9170: 	if ($plain ne '') {
                   9171: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9172: 	    $packagetab{$short}=$plain; 
                   9173: 	}
1.11      www      9174:     }
1.448     albertel 9175:     close($config);
1.329     matthew  9176: }
                   9177: 
                   9178: # ------------- set up temporary directory
                   9179: {
                   9180:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9181: 
1.11      www      9182: }
                   9183: 
1.794     albertel 9184: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9185: 				'compress_threshold'=> 20_000,
                   9186:  			        });
1.185     www      9187: 
1.281     www      9188: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9189: $dumpcount=0;
1.958     www      9190: $locknum=0;
1.22      www      9191: 
1.163     harris41 9192: &logtouch();
1.672     albertel 9193: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9194: $readit=1;
1.564     albertel 9195:     {
                   9196: 	use integer;
                   9197: 	my $test=(2**32)+1;
1.568     albertel 9198: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9199: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9200:     }
1.195     www      9201: }
1.1       albertel 9202: }
1.179     www      9203: 
1.1       albertel 9204: 1;
1.191     harris41 9205: __END__
                   9206: 
1.243     albertel 9207: =pod
                   9208: 
1.191     harris41 9209: =head1 NAME
                   9210: 
1.243     albertel 9211: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9212: 
                   9213: =head1 SYNOPSIS
                   9214: 
1.243     albertel 9215: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9216: 
                   9217:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9218: 
1.243     albertel 9219: Common parameters:
                   9220: 
                   9221: =over 4
                   9222: 
                   9223: =item *
                   9224: 
                   9225: $uname : an internal username (if $cname expecting a course Id specifically)
                   9226: 
                   9227: =item *
                   9228: 
                   9229: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9230: 
                   9231: =item *
                   9232: 
                   9233: $symb : a resource instance identifier
                   9234: 
                   9235: =item *
                   9236: 
                   9237: $namespace : the name of a .db file that contains the data needed or
                   9238: being set.
                   9239: 
                   9240: =back
                   9241: 
1.394     bowersj2 9242: =head1 OVERVIEW
1.191     harris41 9243: 
1.394     bowersj2 9244: lonnet provides subroutines which interact with the
                   9245: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9246: about classes, users, and resources.
1.243     albertel 9247: 
                   9248: For many of these objects you can also use this to store data about
                   9249: them or modify them in various ways.
1.191     harris41 9250: 
1.394     bowersj2 9251: =head2 Symbs
1.191     harris41 9252: 
1.394     bowersj2 9253: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9254: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9255: map, the resource number of the resource in the map, and the URL of
                   9256: the resource itself. The latter is somewhat redundant, but might help
                   9257: if maps change.
                   9258: 
                   9259: An example is
                   9260: 
                   9261:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9262: 
                   9263: The respective map entry is
                   9264: 
                   9265:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9266:   title="Problem 2">
                   9267:  </resource>
                   9268: 
                   9269: Symbs are used by the random number generator, as well as to store and
                   9270: restore data specific to a certain instance of for example a problem.
                   9271: 
                   9272: =head2 Storing And Retrieving Data
                   9273: 
                   9274: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9275: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9276: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9277: is is the non-critical message twin of cstore. These functions are for
                   9278: handlers to store a perl hash to a user's permanent data space in an
                   9279: easy manner, and to retrieve it again on another call. It is expected
                   9280: that a handler would use this once at the beginning to retrieve data,
                   9281: and then again once at the end to send only the new data back.
                   9282: 
                   9283: The data is stored in the user's data directory on the user's
                   9284: homeserver under the ID of the course.
                   9285: 
                   9286: The hash that is returned by restore will have all of the previous
                   9287: value for all of the elements of the hash.
                   9288: 
                   9289: Example:
                   9290: 
                   9291:  #creating a hash
                   9292:  my %hash;
                   9293:  $hash{'foo'}='bar';
                   9294: 
                   9295:  #storing it
                   9296:  &Apache::lonnet::cstore(\%hash);
                   9297: 
                   9298:  #changing a value
                   9299:  $hash{'foo'}='notbar';
                   9300: 
                   9301:  #adding a new value
                   9302:  $hash{'bar'}='foo';
                   9303:  &Apache::lonnet::cstore(\%hash);
                   9304: 
                   9305:  #retrieving the hash
                   9306:  my %history=&Apache::lonnet::restore();
                   9307: 
                   9308:  #print the hash
                   9309:  foreach my $key (sort(keys(%history))) {
                   9310:    print("\%history{$key} = $history{$key}");
                   9311:  }
                   9312: 
                   9313: Will print out:
1.191     harris41 9314: 
1.394     bowersj2 9315:  %history{1:foo} = bar
                   9316:  %history{1:keys} = foo:timestamp
                   9317:  %history{1:timestamp} = 990455579
                   9318:  %history{2:bar} = foo
                   9319:  %history{2:foo} = notbar
                   9320:  %history{2:keys} = foo:bar:timestamp
                   9321:  %history{2:timestamp} = 990455580
                   9322:  %history{bar} = foo
                   9323:  %history{foo} = notbar
                   9324:  %history{timestamp} = 990455580
                   9325:  %history{version} = 2
                   9326: 
                   9327: Note that the special hash entries C<keys>, C<version> and
                   9328: C<timestamp> were added to the hash. C<version> will be equal to the
                   9329: total number of versions of the data that have been stored. The
                   9330: C<timestamp> attribute will be the UNIX time the hash was
                   9331: stored. C<keys> is available in every historical section to list which
                   9332: keys were added or changed at a specific historical revision of a
                   9333: hash.
                   9334: 
                   9335: B<Warning>: do not store the hash that restore returns directly. This
                   9336: will cause a mess since it will restore the historical keys as if the
                   9337: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9338: 
1.394     bowersj2 9339: Calling convention:
1.191     harris41 9340: 
1.394     bowersj2 9341:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9342:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9343: 
1.394     bowersj2 9344: For more detailed information, see lonnet specific documentation.
1.191     harris41 9345: 
1.394     bowersj2 9346: =head1 RETURN MESSAGES
1.191     harris41 9347: 
1.394     bowersj2 9348: =over 4
1.191     harris41 9349: 
1.394     bowersj2 9350: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9351: 
1.394     bowersj2 9352: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9353: when the connection is brought back up
1.191     harris41 9354: 
1.394     bowersj2 9355: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9356: for later delivery
1.191     harris41 9357: 
1.967     bisitz   9358: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9359: 
1.394     bowersj2 9360: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9361: that was requested
1.191     harris41 9362: 
1.243     albertel 9363: =back
1.191     harris41 9364: 
1.243     albertel 9365: =head1 PUBLIC SUBROUTINES
1.191     harris41 9366: 
1.243     albertel 9367: =head2 Session Environment Functions
1.191     harris41 9368: 
1.243     albertel 9369: =over 4
1.191     harris41 9370: 
1.394     bowersj2 9371: =item * 
                   9372: X<appenv()>
1.949     raeburn  9373: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9374: the user envirnoment file, and will be restored for each access this
1.620     albertel 9375: user makes during this session, also modifies the %env for the current
1.949     raeburn  9376: process. Optional rolesarrayref - if defined contains a reference to an array
                   9377: of roles which are exempt from the restriction on modifying user.role entries 
                   9378: in the user's environment.db and in %env.    
1.191     harris41 9379: 
                   9380: =item *
1.394     bowersj2 9381: X<delenv()>
1.987     raeburn  9382: B<delenv($delthis,$regexp)>: removes all items from the session
                   9383: environment file that begin with $delthis. If the 
                   9384: optional second arg - $regexp - is true, $delthis is treated as a 
                   9385: regular expression, otherwise \Q$delthis\E is used. 
                   9386: The values are also deleted from the current processes %env.
1.191     harris41 9387: 
1.795     albertel 9388: =item * get_env_multiple($name) 
                   9389: 
                   9390: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9391: values may be defined and end up as an array ref.
                   9392: 
                   9393: returns an array of values
                   9394: 
1.243     albertel 9395: =back
                   9396: 
                   9397: =head2 User Information
1.191     harris41 9398: 
1.243     albertel 9399: =over 4
1.191     harris41 9400: 
                   9401: =item *
1.394     bowersj2 9402: X<queryauthenticate()>
                   9403: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9404: authentication scheme
                   9405: 
                   9406: =item *
1.394     bowersj2 9407: X<authenticate()>
                   9408: B<authenticate($uname,$upass,$udom)>: try to
                   9409: authenticate user from domain's lib servers (first use the current
                   9410: one). C<$upass> should be the users password.
1.191     harris41 9411: 
                   9412: =item *
1.394     bowersj2 9413: X<homeserver()>
                   9414: B<homeserver($uname,$udom)>: find the server which has
                   9415: the user's directory and files (there must be only one), this caches
                   9416: the answer, and also caches if there is a borken connection.
1.191     harris41 9417: 
                   9418: =item *
1.394     bowersj2 9419: X<idget()>
                   9420: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9421: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9422: username, and only 1 username per ID in a specific domain) (returns
                   9423: hash: id=>name,id=>name)
1.191     harris41 9424: 
                   9425: =item *
1.394     bowersj2 9426: X<idrget()>
                   9427: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9428: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9429: 
                   9430: =item *
1.394     bowersj2 9431: X<idput()>
                   9432: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9433: 
                   9434: =item *
1.394     bowersj2 9435: X<rolesinit()>
                   9436: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9437: 
                   9438: =item *
1.551     albertel 9439: X<getsection()>
                   9440: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9441: course $cname, return section name/number or '' for "not in course"
                   9442: and '-1' for "no section"
                   9443: 
                   9444: =item *
1.394     bowersj2 9445: X<userenvironment()>
                   9446: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9447: passed in @what from the requested user's environment, returns a hash
                   9448: 
1.858     raeburn  9449: =item * 
                   9450: X<userlog_query()>
1.859     albertel 9451: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9452: activity.log file. %filters defines filters applied when parsing the
                   9453: log file. These can be start or end timestamps, or the type of action
                   9454: - log to look for Login or Logout events, check for Checkin or
                   9455: Checkout, role for role selection. The response is in the form
                   9456: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9457: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9458: 
1.243     albertel 9459: =back
                   9460: 
                   9461: =head2 User Roles
                   9462: 
                   9463: =over 4
                   9464: 
                   9465: =item *
                   9466: 
1.810     raeburn  9467: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9468:  F: full access
                   9469:  U,I,K: authentication modes (cxx only)
                   9470:  '': forbidden
                   9471:  1: user needs to choose course
                   9472:  2: browse allowed
1.766     albertel 9473:  A: passphrase authentication needed
1.243     albertel 9474: 
                   9475: =item *
                   9476: 
                   9477: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9478: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9479: and course level
                   9480: 
                   9481: =item *
                   9482: 
1.988     raeburn  9483: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9484: (rolesplain.tab); plain text explanation of a user role term.
                   9485: $type is Course (default) or Group.
                   9486: If $forcedefault evaluates to true, text returned will be default 
                   9487: text for $type. Otherwise, if this is a course, the text returned 
                   9488: will be a custom name for the role (if defined in the course's 
                   9489: environment).  If no custom name is defined the default is returned.
                   9490:    
1.832     raeburn  9491: =item *
                   9492: 
1.935     raeburn  9493: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9494: All arguments are optional. Returns a hash of a roles, either for
                   9495: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9496: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9497: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9498: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9499: For each key, value is set to colon-separated start and end times for
                   9500: the role.  If no username and domain are specified, will default to
1.934     raeburn  9501: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9502: of role statuses (active, future or previous), roles 
                   9503: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9504: to restrict the list of roles reported. If no array ref is 
                   9505: provided for types, will default to return only active roles.
1.834     albertel 9506: 
1.243     albertel 9507: =back
                   9508: 
                   9509: =head2 User Modification
                   9510: 
                   9511: =over 4
                   9512: 
                   9513: =item *
                   9514: 
1.957     raeburn  9515: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9516: user for the level given by URL.  Optional start and end dates (leave empty
                   9517: string or zero for "no date")
1.191     harris41 9518: 
                   9519: =item *
                   9520: 
1.243     albertel 9521: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9522: change a users, password, possible return values are: ok,
                   9523: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9524: refused
1.191     harris41 9525: 
                   9526: =item *
                   9527: 
1.243     albertel 9528: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9529: 
                   9530: =item *
                   9531: 
1.963     raeburn  9532: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9533:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9534: modify user
1.191     harris41 9535: 
                   9536: =item *
                   9537: 
1.286     matthew  9538: modifystudent
                   9539: 
1.957     raeburn  9540: modify a student's enrollment and identification information.
1.286     matthew  9541: The course id is resolved based on the current users environment.  
                   9542: This means the envoking user must be a course coordinator or otherwise
                   9543: associated with a course.
                   9544: 
1.297     matthew  9545: This call is essentially a wrapper for lonnet::modifyuser and
                   9546: lonnet::modify_student_enrollment
1.286     matthew  9547: 
                   9548: Inputs: 
                   9549: 
                   9550: =over 4
                   9551: 
1.957     raeburn  9552: =item B<$udom> Student's loncapa domain
1.286     matthew  9553: 
1.957     raeburn  9554: =item B<$uname> Student's loncapa login name
1.286     matthew  9555: 
1.964     bisitz   9556: =item B<$uid> Student/Employee ID
1.286     matthew  9557: 
1.957     raeburn  9558: =item B<$umode> Student's authentication mode
1.286     matthew  9559: 
1.957     raeburn  9560: =item B<$upass> Student's password
1.286     matthew  9561: 
1.957     raeburn  9562: =item B<$first> Student's first name
1.286     matthew  9563: 
1.957     raeburn  9564: =item B<$middle> Student's middle name
1.286     matthew  9565: 
1.957     raeburn  9566: =item B<$last> Student's last name
1.286     matthew  9567: 
1.957     raeburn  9568: =item B<$gene> Student's generation
1.286     matthew  9569: 
1.957     raeburn  9570: =item B<$usec> Student's section in course
1.286     matthew  9571: 
                   9572: =item B<$end> Unix time of the roles expiration
                   9573: 
                   9574: =item B<$start> Unix time of the roles start date
                   9575: 
                   9576: =item B<$forceid> If defined, allow $uid to be changed
                   9577: 
                   9578: =item B<$desiredhome> server to use as home server for student
                   9579: 
1.957     raeburn  9580: =item B<$email> Student's permanent e-mail address
                   9581: 
                   9582: =item B<$type> Type of enrollment (auto or manual)
                   9583: 
1.963     raeburn  9584: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9585: 
                   9586: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9587: 
1.963     raeburn  9588: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9589: 
1.963     raeburn  9590: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9591: 
1.963     raeburn  9592: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9593: 
1.286     matthew  9594: =back
1.297     matthew  9595: 
                   9596: =item *
                   9597: 
                   9598: modify_student_enrollment
                   9599: 
                   9600: Change a students enrollment status in a class.  The environment variable
                   9601: 'role.request.course' must be defined for this function to proceed.
                   9602: 
                   9603: Inputs:
                   9604: 
                   9605: =over 4
                   9606: 
                   9607: =item $udom, students domain
                   9608: 
                   9609: =item $uname, students name
                   9610: 
                   9611: =item $uid, students user id
                   9612: 
                   9613: =item $first, students first name
                   9614: 
                   9615: =item $middle
                   9616: 
                   9617: =item $last
                   9618: 
                   9619: =item $gene
                   9620: 
                   9621: =item $usec
                   9622: 
                   9623: =item $end
                   9624: 
                   9625: =item $start
                   9626: 
1.957     raeburn  9627: =item $type
                   9628: 
                   9629: =item $locktype
                   9630: 
                   9631: =item $cid
                   9632: 
                   9633: =item $selfenroll
                   9634: 
                   9635: =item $context
                   9636: 
1.297     matthew  9637: =back
                   9638: 
1.191     harris41 9639: 
                   9640: =item *
                   9641: 
1.243     albertel 9642: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9643: custom role; give a custom role to a user for the level given by URL.  Specify
                   9644: name and domain of role author, and role name
1.191     harris41 9645: 
                   9646: =item *
                   9647: 
1.243     albertel 9648: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9649: 
                   9650: =item *
                   9651: 
1.243     albertel 9652: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9653: 
                   9654: =back
                   9655: 
                   9656: =head2 Course Infomation
                   9657: 
                   9658: =over 4
1.191     harris41 9659: 
                   9660: =item *
                   9661: 
1.631     albertel 9662: coursedescription($courseid) : returns a hash of information about the
                   9663: specified course id, including all environment settings for the
                   9664: course, the description of the course will be in the hash under the
                   9665: key 'description'
1.191     harris41 9666: 
                   9667: =item *
                   9668: 
1.624     albertel 9669: resdata($name,$domain,$type,@which) : request for current parameter
                   9670: setting for a specific $type, where $type is either 'course' or 'user',
                   9671: @what should be a list of parameters to ask about. This routine caches
                   9672: answers for 5 minutes.
1.243     albertel 9673: 
1.877     foxr     9674: =item *
                   9675: 
                   9676: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9677: data base, returning a hash that is keyed by the resource name and has
                   9678: values that are the resource value.  I believe that the timestamps and
                   9679: versions are also returned.
                   9680: 
                   9681: 
1.243     albertel 9682: =back
                   9683: 
                   9684: =head2 Course Modification
                   9685: 
                   9686: =over 4
1.191     harris41 9687: 
                   9688: =item *
                   9689: 
1.243     albertel 9690: writecoursepref($courseid,%prefs) : write preferences (environment
                   9691: database) for a course
1.191     harris41 9692: 
                   9693: =item *
                   9694: 
1.243     albertel 9695: createcourse($udom,$description,$url) : make/modify course
                   9696: 
                   9697: =back
                   9698: 
                   9699: =head2 Resource Subroutines
                   9700: 
                   9701: =over 4
1.191     harris41 9702: 
                   9703: =item *
                   9704: 
1.243     albertel 9705: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9706: 
                   9707: =item *
                   9708: 
1.243     albertel 9709: repcopy($filename) : subscribes to the requested file, and attempts to
                   9710: replicate from the owning library server, Might return
1.607     raeburn  9711: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9712: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9713: resource. Expects the local filesystem pathname
                   9714: (/home/httpd/html/res/....)
                   9715: 
                   9716: =back
                   9717: 
                   9718: =head2 Resource Information
                   9719: 
                   9720: =over 4
1.191     harris41 9721: 
                   9722: =item *
                   9723: 
1.243     albertel 9724: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9725: a vairety of different possible values, $varname should be a request
                   9726: string, and the other parameters can be used to specify who and what
                   9727: one is asking about.
                   9728: 
                   9729: Possible values for $varname are environment.lastname (or other item
                   9730: from the envirnment hash), user.name (or someother aspect about the
                   9731: user), resource.0.maxtries (or some other part and parameter of a
                   9732: resource)
1.204     albertel 9733: 
                   9734: =item *
                   9735: 
1.243     albertel 9736: directcondval($number) : get current value of a condition; reads from a state
                   9737: string
1.204     albertel 9738: 
                   9739: =item *
                   9740: 
1.243     albertel 9741: condval($condidx) : value of condition index based on state
1.204     albertel 9742: 
                   9743: =item *
                   9744: 
1.243     albertel 9745: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9746: resource's metadata, $what should be either a specific key, or either
                   9747: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9748: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9749: 
                   9750: this function automatically caches all requests
1.191     harris41 9751: 
                   9752: =item *
                   9753: 
1.243     albertel 9754: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9755: network of library servers; returns file handle of where SQL and regex results
                   9756: will be stored for query
1.191     harris41 9757: 
                   9758: =item *
                   9759: 
1.243     albertel 9760: symbread($filename) : return symbolic list entry (filename argument optional);
                   9761: returns the data handle
1.191     harris41 9762: 
                   9763: =item *
                   9764: 
1.243     albertel 9765: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9766: a possible symb for the URL in $thisfn, and if is an encryypted
                   9767: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9768: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9769: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9770: 
1.191     harris41 9771: 
                   9772: =item *
                   9773: 
1.243     albertel 9774: symbclean($symb) : removes versions numbers from a symb, returns the
                   9775: cleaned symb
1.191     harris41 9776: 
                   9777: =item *
                   9778: 
1.243     albertel 9779: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9780: course map, user must be in a course for it to work.
1.191     harris41 9781: 
                   9782: =item *
                   9783: 
1.243     albertel 9784: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9785: 
                   9786: =item *
                   9787: 
1.243     albertel 9788: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9789: a random seed, all arguments are optional, if they aren't sent it uses the
                   9790: environment to derive them. Note: if symb isn't sent and it can't get one
                   9791: from &symbread it will use the current time as its return value
1.191     harris41 9792: 
                   9793: =item *
                   9794: 
1.243     albertel 9795: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9796: unfakeable, receipt
1.191     harris41 9797: 
                   9798: =item *
                   9799: 
1.620     albertel 9800: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9801: 
                   9802: =item *
                   9803: 
1.243     albertel 9804: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9805: 
                   9806: =item *
                   9807: 
1.243     albertel 9808: 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 9809: 
                   9810: =item *
                   9811: 
1.243     albertel 9812: 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 9813: 
                   9814: =item *
                   9815: 
1.243     albertel 9816: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9817: 
                   9818: =item *
                   9819: 
1.243     albertel 9820: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9821: forcing spreadsheet to reevaluate the resource scores next time.
                   9822: 
                   9823: =back
                   9824: 
                   9825: =head2 Storing/Retreiving Data
                   9826: 
                   9827: =over 4
1.191     harris41 9828: 
                   9829: =item *
                   9830: 
1.243     albertel 9831: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9832: for this url; hashref needs to be given and should be a \%hashname; the
                   9833: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9834: be derived from the env
1.191     harris41 9835: 
                   9836: =item *
                   9837: 
1.243     albertel 9838: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9839: uses critical subroutine
1.191     harris41 9840: 
                   9841: =item *
                   9842: 
1.243     albertel 9843: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9844: all args are optional
1.191     harris41 9845: 
                   9846: =item *
                   9847: 
1.717     albertel 9848: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9849: dumps the complete (or key matching regexp) namespace into a hash
                   9850: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9851: normally &store()ed into
                   9852: 
                   9853: $range should be either an integer '100' (give me the first 100
                   9854:                                            matching records)
                   9855:               or be  two integers sperated by a - with no spaces
                   9856:                  '30-50' (give me the 30th through the 50th matching
                   9857:                           records)
                   9858: 
                   9859: 
                   9860: =item *
                   9861: 
                   9862: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9863: replaces a &store() version of data with a replacement set of data
                   9864: for a particular resource in a namespace passed in the $storehash hash 
                   9865: reference
                   9866: 
                   9867: =item *
                   9868: 
1.243     albertel 9869: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9870: works very similar to store/cstore, but all data is stored in a
                   9871: temporary location and can be reset using tmpreset, $storehash should
                   9872: be a hash reference, returns nothing on success
1.191     harris41 9873: 
                   9874: =item *
                   9875: 
1.243     albertel 9876: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9877: similar to restore, but all data is stored in a temporary location and
                   9878: can be reset using tmpreset. Returns a hash of values on success,
                   9879: error string otherwise.
1.191     harris41 9880: 
                   9881: =item *
                   9882: 
1.243     albertel 9883: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9884: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9885: 
                   9886: =item *
                   9887: 
1.243     albertel 9888: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9889: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9890: 
                   9891: =item *
                   9892: 
1.243     albertel 9893: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9894: namesp ($udom and $uname are optional)
1.191     harris41 9895: 
                   9896: =item *
                   9897: 
1.702     albertel 9898: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9899: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9900: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9901: 
1.702     albertel 9902: $range should be either an integer '100' (give me the first 100
                   9903:                                            matching records)
                   9904:               or be  two integers sperated by a - with no spaces
                   9905:                  '30-50' (give me the 30th through the 50th matching
                   9906:                           records)
1.449     matthew  9907: =item *
                   9908: 
                   9909: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9910: $store can be a scalar, an array reference, or if the amount to be 
                   9911: incremented is > 1, a hash reference.
                   9912: 
                   9913: ($udom and $uname are optional)
1.191     harris41 9914: 
                   9915: =item *
                   9916: 
1.243     albertel 9917: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9918: ($udom and $uname are optional)
1.191     harris41 9919: 
                   9920: =item *
                   9921: 
1.243     albertel 9922: cput($namespace,$storehash,$udom,$uname) : critical put
                   9923: ($udom and $uname are optional)
1.191     harris41 9924: 
                   9925: =item *
                   9926: 
1.748     albertel 9927: newput($namespace,$storehash,$udom,$uname) :
                   9928: 
                   9929: Attempts to store the items in the $storehash, but only if they don't
                   9930: currently exist, if this succeeds you can be certain that you have 
                   9931: successfully created a new key value pair in the $namespace db.
                   9932: 
                   9933: 
                   9934: Args:
                   9935:  $namespace: name of database to store values to
                   9936:  $storehash: hashref to store to the db
                   9937:  $udom: (optional) domain of user containing the db
                   9938:  $uname: (optional) name of user caontaining the db
                   9939: 
                   9940: Returns:
                   9941:  'ok' -> succeeded in storing all keys of $storehash
                   9942:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9943:                         least <key> already existed in the db (other
                   9944:                         requested keys may also already exist)
1.967     bisitz   9945:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9946:  'con_lost' -> unable to contact request server
                   9947:  'refused' -> action was not allowed by remote machine
                   9948: 
                   9949: 
                   9950: =item *
                   9951: 
1.243     albertel 9952: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9953: reference filled in from namesp (encrypts the return communication)
                   9954: ($udom and $uname are optional)
1.191     harris41 9955: 
                   9956: =item *
                   9957: 
1.243     albertel 9958: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9959: critical subroutine
                   9960: 
1.806     raeburn  9961: =item *
                   9962: 
1.860     raeburn  9963: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9964: array reference filled in from namespace found in domain level on either
                   9965: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9966: 
                   9967: =item *
                   9968: 
1.860     raeburn  9969: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9970: domain level either on specified domain server ($uhome) or primary domain 
                   9971: server ($udom and $uhome are optional)
1.806     raeburn  9972: 
1.943     raeburn  9973: =item * 
                   9974: 
                   9975: get_domain_defaults($target_domain) : returns hash with defaults for
                   9976: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9977: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9978: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9979: Values are retrieved from cache (if current), or from domain's configuration.db
                   9980: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9981: or lonTabs/domain.tab. 
                   9982: 
                   9983: %domdefaults = &get_auth_defaults($target_domain);
                   9984: 
1.243     albertel 9985: =back
                   9986: 
                   9987: =head2 Network Status Functions
                   9988: 
                   9989: =over 4
1.191     harris41 9990: 
                   9991: =item *
                   9992: 
                   9993: dirlist($uri) : return directory list based on URI
                   9994: 
                   9995: =item *
                   9996: 
1.243     albertel 9997: spareserver() : find server with least workload from spare.tab
                   9998: 
1.986     foxr     9999: 
                   10000: =item *
                   10001: 
                   10002: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10003: if there is no corresponding loncapa host.
                   10004: 
1.243     albertel 10005: =back
                   10006: 
1.986     foxr     10007: 
1.243     albertel 10008: =head2 Apache Request
                   10009: 
                   10010: =over 4
1.191     harris41 10011: 
                   10012: =item *
                   10013: 
1.243     albertel 10014: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10015: localhost, posts hash
                   10016: 
                   10017: =back
                   10018: 
                   10019: =head2 Data to String to Data
                   10020: 
                   10021: =over 4
1.191     harris41 10022: 
                   10023: =item *
                   10024: 
1.243     albertel 10025: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10026: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10027: 
                   10028: =item *
                   10029: 
1.243     albertel 10030: hashref2str($hashref) : convert a hashref into a string complete with
                   10031: escaping and '=' and '&' separators, supports elements that are
                   10032: arrayrefs and hashrefs
1.191     harris41 10033: 
                   10034: =item *
                   10035: 
1.243     albertel 10036: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10037: with escaping and '&' separators, supports elements that are arrayrefs
                   10038: and hashrefs
1.191     harris41 10039: 
                   10040: =item *
                   10041: 
1.243     albertel 10042: str2hash($string) : convert string to hash using unescaping and
                   10043: splitting on '=' and '&', supports elements that are arrayrefs and
                   10044: hashrefs
1.191     harris41 10045: 
                   10046: =item *
                   10047: 
1.243     albertel 10048: str2array($string) : convert string to hash using unescaping and
                   10049: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10050: 
                   10051: =back
                   10052: 
                   10053: =head2 Logging Routines
                   10054: 
                   10055: =over 4
                   10056: 
                   10057: These routines allow one to make log messages in the lonnet.log and
                   10058: lonnet.perm logfiles.
1.191     harris41 10059: 
                   10060: =item *
                   10061: 
1.243     albertel 10062: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10063: 
                   10064: =item *
                   10065: 
1.243     albertel 10066: logthis() : append message to the normal lonnet.log file, it gets
                   10067: preiodically rolled over and deleted.
1.191     harris41 10068: 
                   10069: =item *
                   10070: 
1.243     albertel 10071: logperm() : append a permanent message to lonnet.perm.log, this log
                   10072: file never gets deleted by any automated portion of the system, only
                   10073: messages of critical importance should go in here.
                   10074: 
                   10075: =back
                   10076: 
                   10077: =head2 General File Helper Routines
                   10078: 
                   10079: =over 4
1.191     harris41 10080: 
                   10081: =item *
                   10082: 
1.481     raeburn  10083: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10084: (a) files in /uploaded
                   10085:   (i) If a local copy of the file exists - 
                   10086:       compares modification date of local copy with last-modified date for 
                   10087:       definitive version stored on home server for course. If local copy is 
                   10088:       stale, requests a new version from the home server and stores it. 
                   10089:       If the original has been removed from the home server, then local copy 
                   10090:       is unlinked.
                   10091:   (ii) If local copy does not exist -
                   10092:       requests the file from the home server and stores it. 
                   10093:   
                   10094:   If $caller is 'uploadrep':  
                   10095:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10096:     for request for files originally uploaded via DOCS. 
                   10097:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10098:   
                   10099:   Otherwise:
                   10100:      This indicates a call from the content generation phase of the request.
                   10101:      -  returns the entire contents of the file or -1.
                   10102:      
                   10103: (b) files in /res
                   10104:    - returns the entire contents of a file or -1; 
                   10105:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10106: 
1.712     albertel 10107: 
                   10108: =item *
                   10109: 
                   10110: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10111:                   reference
                   10112: 
                   10113: returns either a stat() list of data about the file or an empty list
                   10114: if the file doesn't exist or couldn't find out about it (connection
                   10115: problems or user unknown)
                   10116: 
1.191     harris41 10117: =item *
                   10118: 
1.243     albertel 10119: filelocation($dir,$file) : returns file system location of a file
                   10120: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10121: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10122: and a file of ../bob will become /a/bob)
1.191     harris41 10123: 
                   10124: =item *
                   10125: 
                   10126: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10127: filelocation except for hrefs
                   10128: 
                   10129: =item *
                   10130: 
                   10131: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10132: 
1.243     albertel 10133: =back
                   10134: 
1.608     albertel 10135: =head2 Usererfile file routines (/uploaded*)
                   10136: 
                   10137: =over 4
                   10138: 
                   10139: =item *
                   10140: 
                   10141: userfileupload(): main rotine for putting a file in a user or course's
                   10142:                   filespace, arguments are,
                   10143: 
1.620     albertel 10144:  formname - required - this is the name of the element in $env where the
1.608     albertel 10145:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10146:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10147:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10148:  coursedoc - if true, store the file in the course of the active role
                   10149:              of the current user
                   10150:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10151:          if undefined, it will be placed in "unknown"
                   10152: 
                   10153:  (This routine calls clean_filename() to remove any dangerous
                   10154:  characters from the filename, and then calls finuserfileupload() to
                   10155:  complete the transaction)
                   10156: 
                   10157:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10158:  and /adm/notfound.html if unsuccessful
                   10159: 
                   10160: =item *
                   10161: 
                   10162: clean_filename(): routine for cleaing a filename up for storage in
                   10163:                  userfile space, argument is:
                   10164: 
                   10165:  filename - proposed filename
                   10166: 
                   10167: returns: the new clean filename
                   10168: 
                   10169: =item *
                   10170: 
                   10171: finishuserfileupload(): routine that creaes and sends the file to
                   10172: userspace, probably shouldn't be called directly
                   10173: 
                   10174:   docuname: username or courseid of destination for the file
                   10175:   docudom: domain of user/course of destination for the file
                   10176:   formname: same as for userfileupload()
                   10177:   fname: filename (inculding subdirectories) for the file
                   10178: 
                   10179:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10180:  and /adm/notfound.html if unsuccessful
                   10181: 
                   10182: =item *
                   10183: 
                   10184: renameuserfile(): renames an existing userfile to a new name
                   10185: 
                   10186:   Args:
                   10187:    docuname: username or courseid of destination for the file
                   10188:    docudom: domain of user/course of destination for the file
                   10189:    old: current file name (including any subdirs under userfiles)
                   10190:    new: desired file name (including any subdirs under userfiles)
                   10191: 
                   10192: =item *
                   10193: 
                   10194: mkdiruserfile(): creates a directory is a userfiles dir
                   10195: 
                   10196:   Args:
                   10197:    docuname: username or courseid of destination for the file
                   10198:    docudom: domain of user/course of destination for the file
                   10199:    dir: dir to create (including any subdirs under userfiles)
                   10200: 
                   10201: =item *
                   10202: 
                   10203: removeuserfile(): removes a file that exists in userfiles
                   10204: 
                   10205:   Args:
                   10206:    docuname: username or courseid of destination for the file
                   10207:    docudom: domain of user/course of destination for the file
                   10208:    fname: filname to delete (including any subdirs under userfiles)
                   10209: 
                   10210: =item *
                   10211: 
                   10212: removeuploadedurl(): convience function for removeuserfile()
                   10213: 
                   10214:   Args:
                   10215:    url:  a full /uploaded/... url to delete
                   10216: 
1.747     albertel 10217: =item * 
                   10218: 
                   10219: get_portfile_permissions():
                   10220:   Args:
                   10221:     domain: domain of user or course contain the portfolio files
                   10222:     user: name of user or num of course contain the portfolio files
                   10223:   Returns:
                   10224:     hashref of a dump of the proper file_permissions.db
                   10225:    
                   10226: 
                   10227: =item * 
                   10228: 
                   10229: get_access_controls():
                   10230: 
                   10231: Args:
                   10232:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10233:   group: (optional) the group you want the files associated with
                   10234:   file: (optional) the file you want access info on
                   10235: 
                   10236: Returns:
1.749     raeburn  10237:     a hash (keys are file names) of hashes containing
                   10238:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10239:         values are XML containing access control settings (see below) 
1.747     albertel 10240: 
                   10241: Internal notes:
                   10242: 
1.749     raeburn  10243:  access controls are stored in file_permissions.db as key=value pairs.
                   10244:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10245:         where scope -> public,guest,course,group,domains or users.
                   10246:               end -> UNIX time for end of access (0 -> no end date)
                   10247:               start -> UNIX time for start of access
                   10248: 
                   10249:     value -> XML description of access control
                   10250:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10251:             <start></start>
                   10252:             <end></end>
                   10253: 
                   10254:             <password></password>  for scope type = guest
                   10255: 
                   10256:             <domain></domain>     for scope type = course or group
                   10257:             <number></number>
                   10258:             <roles id="">
                   10259:              <role></role>
                   10260:              <access></access>
                   10261:              <section></section>
                   10262:              <group></group>
                   10263:             </roles>
                   10264: 
                   10265:             <dom></dom>         for scope type = domains
                   10266: 
                   10267:             <users>             for scope type = users
                   10268:              <user>
                   10269:               <uname></uname>
                   10270:               <udom></udom>
                   10271:              </user>
                   10272:             </users>
                   10273:            </scope> 
                   10274:               
                   10275:  Access data is also aggregated for each file in an additional key=value pair:
                   10276:  key -> path to file/file_name\0accesscontrol 
                   10277:  value -> reference to hash
                   10278:           hash contains key = value pairs
                   10279:           where key = uniqueID:scope_end_start
                   10280:                 value = UNIX time record was last updated
                   10281: 
                   10282:           Used to improve speed of look-ups of access controls for each file.  
                   10283:  
                   10284:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10285: 
                   10286: modify_access_controls():
                   10287: 
                   10288: Modifies access controls for a portfolio file
                   10289: Args
                   10290: 1. file name
                   10291: 2. reference to hash of required changes,
                   10292: 3. domain
                   10293: 4. username
                   10294:   where domain,username are the domain of the portfolio owner 
                   10295:   (either a user or a course) 
                   10296: 
                   10297: Returns:
                   10298: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10299: 2. result of deletions ('ok' or 'error', with error message).
                   10300: 3. reference to hash of any new or updated access controls.
                   10301: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10302:    key = integer (inbound ID)
                   10303:    value = uniqueID  
1.747     albertel 10304: 
1.608     albertel 10305: =back
                   10306: 
1.243     albertel 10307: =head2 HTTP Helper Routines
                   10308: 
                   10309: =over 4
                   10310: 
1.191     harris41 10311: =item *
                   10312: 
                   10313: escape() : unpack non-word characters into CGI-compatible hex codes
                   10314: 
                   10315: =item *
                   10316: 
                   10317: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10318: 
1.243     albertel 10319: =back
                   10320: 
                   10321: =head1 PRIVATE SUBROUTINES
                   10322: 
                   10323: =head2 Underlying communication routines (Shouldn't call)
                   10324: 
                   10325: =over 4
                   10326: 
                   10327: =item *
                   10328: 
                   10329: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10330: 
                   10331: =item *
                   10332: 
                   10333: reply() : uses subreply to send a message to remote machine, logs all failures
                   10334: 
                   10335: =item *
                   10336: 
                   10337: critical() : passes a critical message to another server; if cannot
                   10338: get through then place message in connection buffer directory and
                   10339: returns con_delayed, if incapable of saving message, returns
                   10340: con_failed
                   10341: 
                   10342: =item *
                   10343: 
                   10344: reconlonc() : tries to reconnect lonc client processes.
                   10345: 
                   10346: =back
                   10347: 
                   10348: =head2 Resource Access Logging
                   10349: 
                   10350: =over 4
                   10351: 
                   10352: =item *
                   10353: 
                   10354: flushcourselogs() : flush (save) buffer logs and access logs
                   10355: 
                   10356: =item *
                   10357: 
                   10358: courselog($what) : save message for course in hash
                   10359: 
                   10360: =item *
                   10361: 
                   10362: courseacclog($what) : save message for course using &courselog().  Perform
                   10363: special processing for specific resource types (problems, exams, quizzes, etc).
                   10364: 
1.191     harris41 10365: =item *
                   10366: 
                   10367: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10368: as a PerlChildExitHandler
1.243     albertel 10369: 
                   10370: =back
                   10371: 
                   10372: =head2 Other
                   10373: 
                   10374: =over 4
                   10375: 
                   10376: =item *
                   10377: 
                   10378: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10379: 
                   10380: =back
                   10381: 
                   10382: =cut
1.877     foxr     10383: 

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