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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1038  ! raeburn     4: # $Id: lonnet.pm,v 1.1037 2009/10/28 19:09:21 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.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.977     amueller  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.993     raeburn   200: sub get_server_loncaparev {
                    201:     my ($dom,$lonhost) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             undef($lonhost);
                    205:         }
                    206:     }
                    207:     if (!defined($lonhost)) {
                    208:         if (defined(&domain($dom,'primary'))) {
                    209:             $lonhost=&domain($dom,'primary');
                    210:             if ($lonhost eq 'no_host') {
                    211:                 undef($lonhost);
                    212:             }
                    213:         }
                    214:     }
                    215:     if (defined($lonhost)) {
                    216:         my $cachetime = 24*3600;
                    217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    218:         if (defined($cached)) {
                    219:             return $loncaparev;
                    220:         } else {
                    221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
                    222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    223:         }
                    224:     }
                    225: }
                    226: 
1.1       albertel  227: # -------------------------------------------------- Non-critical communication
                    228: sub subreply {
                    229:     my ($cmd,$server)=@_;
1.838     albertel  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      231:     #
                    232:     #  With loncnew process trimming, there's a timing hole between lonc server
                    233:     #  process exit and the master server picking up the listen on the AF_UNIX
                    234:     #  socket.  In that time interval, a lock file will exist:
                    235: 
                    236:     my $lockfile=$peerfile.".lock";
                    237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    238: 	sleep(1);
                    239:     }
                    240:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      241:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      242:     #
1.550     foxr      243:     #   We'll give the connection a few tries before abandoning it.  If
                    244:     #   connection is not possible, we'll con_lost back to the client.
                    245:     #   
                    246:     my $client;
                    247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    249: 				      Type    => SOCK_STREAM,
                    250: 				      Timeout => 10);
1.869     albertel  251: 	if ($client) {
1.550     foxr      252: 	    last;		# Connected!
1.850     albertel  253: 	} else {
1.853     albertel  254: 	    &create_connection(&hostname($server),$server);
1.550     foxr      255: 	}
1.850     albertel  256:         sleep(1);		# Try again later if failed connection.
1.550     foxr      257:     }
                    258:     my $answer;
                    259:     if ($client) {
1.704     albertel  260: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      261: 	$answer=<$client>;
                    262: 	if (!$answer) { $answer="con_lost"; }
                    263: 	chomp($answer);
                    264:     } else {
                    265: 	$answer = 'con_lost';	# Failed connection.
                    266:     }
1.1       albertel  267:     return $answer;
                    268: }
                    269: 
                    270: sub reply {
                    271:     my ($cmd,$server)=@_;
1.838     albertel  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  273:     my $answer=subreply($cmd,$server);
1.65      www       274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  275:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       276:                 " $cmd to $server returned $answer</font>");
                    277:     }
1.1       albertel  278:     return $answer;
                    279: }
                    280: 
                    281: # ----------------------------------------------------------- Send USR1 to lonc
                    282: 
                    283: sub reconlonc {
1.891     albertel  284:     my ($lonid) = @_;
                    285:     my $hostname = &hostname($lonid);
                    286:     if ($lonid) {
                    287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    288: 	if ($hostname && -e $peerfile) {
                    289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    291: 					     Type    => SOCK_STREAM,
                    292: 					     Timeout => 10);
                    293: 	    if ($client) {
                    294: 		print $client ("reset_retries\n");
                    295: 		my $answer=<$client>;
                    296: 		#reset just this one.
                    297: 	    }
                    298: 	}
                    299: 	return;
                    300:     }
                    301: 
1.836     www       302:     &logthis("Trying to reconnect lonc");
1.1       albertel  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  304:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  305: 	my $loncpid=<$fh>;
                    306:         chomp($loncpid);
                    307:         if (kill 0 => $loncpid) {
                    308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    309:             kill USR1 => $loncpid;
                    310:             sleep 1;
1.836     www       311:          } else {
1.12      www       312: 	    &logthis(
1.672     albertel  313:                "<font color=\"blue\">WARNING:".
1.12      www       314:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  315:         }
                    316:     } else {
1.836     www       317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  318:     }
                    319: }
                    320: 
                    321: # ------------------------------------------------------ Critical communication
1.12      www       322: 
1.1       albertel  323: sub critical {
                    324:     my ($cmd,$server)=@_;
1.838     albertel  325:     unless (&hostname($server)) {
1.672     albertel  326:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       327:                " Critical message to unknown server ($server)</font>");
                    328:         return 'no_such_host';
                    329:     }
1.1       albertel  330:     my $answer=reply($cmd,$server);
                    331:     if ($answer eq 'con_lost') {
                    332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  333: 	my $answer=reply($cmd,$server);
1.1       albertel  334:         if ($answer eq 'con_lost') {
                    335:             my $now=time;
                    336:             my $middlename=$cmd;
1.5       www       337:             $middlename=substr($middlename,0,16);
1.1       albertel  338:             $middlename=~s/\W//g;
                    339:             my $dfilename=
1.305     www       340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    341:             $dumpcount++;
1.1       albertel  342:             {
1.448     albertel  343: 		my $dfh;
                    344: 		if (open($dfh,">$dfilename")) {
                    345: 		    print $dfh "$cmd\n"; 
                    346: 		    close($dfh);
                    347: 		}
1.1       albertel  348:             }
                    349:             sleep 2;
                    350:             my $wcmd='';
                    351:             {
1.448     albertel  352: 		my $dfh;
                    353: 		if (open($dfh,"<$dfilename")) {
                    354: 		    $wcmd=<$dfh>; 
                    355: 		    close($dfh);
                    356: 		}
1.1       albertel  357:             }
                    358:             chomp($wcmd);
1.7       www       359:             if ($wcmd eq $cmd) {
1.672     albertel  360: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       361:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  362:                 &logperm("D:$server:$cmd");
                    363: 	        return 'con_delayed';
                    364:             } else {
1.672     albertel  365:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       366:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  367:                 &logperm("F:$server:$cmd");
                    368:                 return 'con_failed';
                    369:             }
                    370:         }
                    371:     }
                    372:     return $answer;
1.405     albertel  373: }
                    374: 
1.755     albertel  375: # ------------------------------------------- check if return value is an error
                    376: 
                    377: sub error {
                    378:     my ($result) = @_;
1.756     albertel  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  380: 	if ($2 == 2) { return undef; }
                    381: 	return $1;
                    382:     }
                    383:     return undef;
                    384: }
                    385: 
1.783     albertel  386: sub convert_and_load_session_env {
                    387:     my ($lonidsdir,$handle)=@_;
                    388:     my @profile;
                    389:     {
1.917     albertel  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    391: 	if (!$opened) {
1.915     albertel  392: 	    return 0;
                    393: 	}
1.783     albertel  394: 	flock($idf,LOCK_SH);
                    395: 	@profile=<$idf>;
                    396: 	close($idf);
                    397:     }
                    398:     my %temp_env;
                    399:     foreach my $line (@profile) {
1.786     albertel  400: 	if ($line !~ m/=/) {
                    401: 	    return 0;
                    402: 	}
1.783     albertel  403: 	chomp($line);
                    404: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    406:     }
                    407:     unlink("$lonidsdir/$handle.id");
                    408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    409: 	    0640)) {
                    410: 	%disk_env = %temp_env;
                    411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    412: 	untie(%disk_env);
                    413:     }
1.786     albertel  414:     return 1;
1.783     albertel  415: }
                    416: 
1.374     www       417: # ------------------------------------------- Transfer profile into environment
1.780     albertel  418: my $env_loaded;
                    419: sub transfer_profile_to_env {
1.788     albertel  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    421:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       422: 
1.720     albertel  423:     if (!defined($lonidsdir)) {
                    424: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    425:     }
                    426:     if (!defined($handle)) {
                    427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    428:     }
                    429: 
1.786     albertel  430:     my $convert;
                    431:     {
1.917     albertel  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433: 	if (!$opened) {
1.915     albertel  434: 	    return;
                    435: 	}
1.786     albertel  436: 	flock($idf,LOCK_SH);
                    437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 		&GDBM_READER(),0640)) {
                    439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    440: 	    untie(%disk_env);
                    441: 	} else {
                    442: 	    $convert = 1;
                    443: 	}
                    444:     }
                    445:     if ($convert) {
                    446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    447: 	    &logthis("Failed to load session, or convert session.");
                    448: 	}
1.374     www       449:     }
1.783     albertel  450: 
1.786     albertel  451:     my %remove;
1.783     albertel  452:     while ( my $envname = each(%env) ) {
1.433     matthew   453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    454:             if ($time < time-300) {
1.783     albertel  455:                 $remove{$key}++;
1.433     matthew   456:             }
                    457:         }
                    458:     }
1.783     albertel  459: 
1.619     albertel  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  461:     $env_loaded=1;
1.783     albertel  462:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   463:         &delenv($expired_key);
1.374     www       464:     }
1.1       albertel  465: }
                    466: 
1.916     albertel  467: # ---------------------------------------------------- Check for valid session 
                    468: sub check_for_valid_session {
                    469:     my ($r) = @_;
                    470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    471:     my $lonid=$cookies{'lonID'};
                    472:     return undef if (!$lonid);
                    473: 
                    474:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    475:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    476:     return undef if (!-e "$lonidsdir/$handle.id");
                    477: 
1.917     albertel  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    479:     return undef if (!$opened);
1.916     albertel  480: 
                    481:     flock($idf,LOCK_SH);
                    482:     my %disk_env;
                    483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    484: 	    &GDBM_READER(),0640)) {
                    485: 	return undef;	
                    486:     }
                    487: 
                    488:     if (!defined($disk_env{'user.name'})
                    489: 	|| !defined($disk_env{'user.domain'})) {
                    490: 	return undef;
                    491:     }
                    492:     return $handle;
                    493: }
                    494: 
1.830     albertel  495: sub timed_flock {
                    496:     my ($file,$lock_type) = @_;
                    497:     my $failed=0;
                    498:     eval {
                    499: 	local $SIG{__DIE__}='DEFAULT';
                    500: 	local $SIG{ALRM}=sub {
                    501: 	    $failed=1;
                    502: 	    die("failed lock");
                    503: 	};
                    504: 	alarm(13);
                    505: 	flock($file,$lock_type);
                    506: 	alarm(0);
                    507:     };
                    508:     if ($failed) {
                    509: 	return undef;
                    510:     } else {
                    511: 	return 1;
                    512:     }
                    513: }
                    514: 
1.5       www       515: # ---------------------------------------------------------- Append Environment
                    516: 
                    517: sub appenv {
1.949     raeburn   518:     my ($newenv,$roles) = @_;
                    519:     if (ref($newenv) eq 'HASH') {
                    520:         foreach my $key (keys(%{$newenv})) {
                    521:             my $refused = 0;
                    522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    523:                 $refused = 1;
                    524:                 if (ref($roles) eq 'ARRAY') {
                    525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    527:                         $refused = 0;
                    528:                     }
                    529:                 }
                    530:             }
                    531:             if ($refused) {
                    532:                 &logthis("<font color=\"blue\">WARNING: ".
                    533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    534:                          .'</font>');
                    535: 	        delete($newenv->{$key});
                    536:             } else {
                    537:                 $env{$key}=$newenv->{$key};
                    538:             }
                    539:         }
                    540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    541:         if ($opened
                    542: 	    && &timed_flock($env_file,LOCK_EX)
                    543: 	    &&
                    544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    546: 	    while (my ($key,$value) = each(%{$newenv})) {
                    547: 	        $disk_env{$key} = $value;
                    548: 	    }
                    549: 	    untie(%disk_env);
1.35      www       550:         }
1.191     harris41  551:     }
1.56      www       552:     return 'ok';
                    553: }
                    554: # ----------------------------------------------------- Delete from Environment
                    555: 
                    556: sub delenv {
1.987     raeburn   557:     my ($delthis,$regexp) = @_;
1.56      www       558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  559:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       560:                 "Attempt to delete from environment ".$delthis);
                    561:         return 'error';
                    562:     }
1.917     albertel  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    564:     if ($opened
1.915     albertel  565: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  566: 	&&
                    567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  569: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   570: 	    if ($regexp) {
                    571:                 if ($key=~/^$delthis/) {
                    572:                     delete($env{$key});
                    573:                     delete($disk_env{$key});
                    574:                 } 
                    575:             } else {
                    576:                 if ($key=~/^\Q$delthis\E/) {
                    577: 		    delete($env{$key});
                    578: 		    delete($disk_env{$key});
                    579: 	        }
                    580:             }
1.448     albertel  581: 	}
1.783     albertel  582: 	untie(%disk_env);
1.5       www       583:     }
                    584:     return 'ok';
1.369     albertel  585: }
                    586: 
1.790     albertel  587: sub get_env_multiple {
                    588:     my ($name) = @_;
                    589:     my @values;
                    590:     if (defined($env{$name})) {
                    591:         # exists is it an array
                    592:         if (ref($env{$name})) {
                    593:             @values=@{ $env{$name} };
                    594:         } else {
                    595:             $values[0]=$env{$name};
                    596:         }
                    597:     }
                    598:     return(@values);
                    599: }
                    600: 
1.958     www       601: # ------------------------------------------------------------------- Locking
                    602: 
                    603: sub set_lock {
                    604:     my ($text)=@_;
                    605:     $locknum++;
                    606:     my $id=$$.'-'.$locknum;
                    607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    608:              'session.lock.'.$id => $text});
                    609:     return $id;
                    610: }
                    611: 
                    612: sub get_locks {
                    613:     my $num=0;
                    614:     my %texts=();
                    615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    616:        if ($lock=~/\w/) {
                    617:           $num++;
                    618:           $texts{$lock}=$env{'session.lock.'.$lock};
                    619:        }
                    620:    }
                    621:    return ($num,%texts);
                    622: }
                    623: 
                    624: sub remove_lock {
                    625:     my ($id)=@_;
                    626:     my $newlocks='';
                    627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    628:        if (($lock=~/\w/) && ($lock ne $id)) {
                    629:           $newlocks.=','.$lock;
                    630:        }
                    631:     }
                    632:     &appenv({'session.locks' => $newlocks});
                    633:     &delenv('session.lock.'.$id);
                    634: }
                    635: 
                    636: sub remove_all_locks {
                    637:     my $activelocks=$env{'session.locks'};
                    638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    639:        if ($lock=~/\w/) {
                    640:           &remove_lock($lock);
                    641:        }
                    642:     }
                    643: }
                    644: 
                    645: 
1.369     albertel  646: # ------------------------------------------ Find out current server userload
                    647: sub userload {
                    648:     my $numusers=0;
                    649:     {
                    650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    651: 	my $filename;
                    652: 	my $curtime=time;
                    653: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  654: 	    next if ($filename eq '.' || $filename eq '..');
                    655: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  658: 	}
                    659: 	closedir(LONIDS);
                    660:     }
                    661:     my $userloadpercent=0;
                    662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    663:     if ($maxuserload) {
1.371     albertel  664: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  665:     }
1.372     albertel  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  667:     return $userloadpercent;
1.283     www       668: }
                    669: 
                    670: # ------------------------------------------ Fight off request when overloaded
                    671: 
                    672: sub overloaderror {
                    673:     my ($r,$checkserver)=@_;
                    674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    675:     my $loadavg;
                    676:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  677:        open(my $loadfile,'/proc/loadavg');
1.283     www       678:        $loadavg=<$loadfile>;
                    679:        $loadavg =~ s/\s.*//g;
1.285     matthew   680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  681:        close($loadfile);
1.283     www       682:     } else {
                    683:        $loadavg=&reply('load',$checkserver);
                    684:     }
1.285     matthew   685:     my $overload=$loadavg-100;
1.283     www       686:     if ($overload>0) {
1.285     matthew   687: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       689:         return 413;
1.283     www       690:     }    
                    691:     return '';
1.5       www       692: }
1.1       albertel  693: 
                    694: # ------------------------------ Find server with least workload from spare.tab
1.11      www       695: 
1.1       albertel  696: sub spareserver {
1.670     albertel  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  698:     my $spare_server;
1.370     albertel  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    701:                                                      :  $userloadpercent;
                    702:     
                    703:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    704: 	($spare_server, $lowest_load) =
                    705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    706:     }
                    707: 
                    708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    709: 
                    710:     if (!$found_server) {
                    711: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    712: 	    ($spare_server, $lowest_load) =
                    713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    714: 	}
                    715:     }
                    716: 
                    717:     if (!$want_server_name) {
1.968     raeburn   718:         my $protocol = 'http';
                    719:         if ($protocol{$spare_server} eq 'https') {
                    720:             $protocol = $protocol{$spare_server};
                    721:         }
1.1001    raeburn   722:         if (defined($spare_server)) {
                    723:             my $hostname = &hostname($spare_server);
                    724:             if (defined($hostname)) {  
                    725: 	        $spare_server = $protocol.'://'.$hostname;
                    726:             }
                    727:         }
1.784     albertel  728:     }
                    729:     return $spare_server;
                    730: }
                    731: 
                    732: sub compare_server_load {
                    733:     my ($try_server, $spare_server, $lowest_load) = @_;
                    734: 
                    735:     my $loadans     = &reply('load',    $try_server);
                    736:     my $userloadans = &reply('userload',$try_server);
                    737: 
                    738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    739: 	next; #didn't get a number from the server
                    740:     }
                    741: 
                    742:     my $load;
                    743:     if ($loadans =~ /\d/) {
                    744: 	if ($userloadans =~ /\d/) {
                    745: 	    #both are numbers, pick the bigger one
                    746: 	    $load = ($loadans > $userloadans) ? $loadans 
                    747: 		                              : $userloadans;
1.411     albertel  748: 	} else {
1.784     albertel  749: 	    $load = $loadans;
1.411     albertel  750: 	}
1.784     albertel  751:     } else {
                    752: 	$load = $userloadans;
                    753:     }
                    754: 
                    755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    756: 	$spare_server = $try_server;
                    757: 	$lowest_load  = $load;
1.370     albertel  758:     }
1.784     albertel  759:     return ($spare_server,$lowest_load);
1.202     matthew   760: }
1.914     albertel  761: 
                    762: # --------------------------- ask offload servers if user already has a session
                    763: sub find_existing_session {
                    764:     my ($udom,$uname) = @_;
                    765:     foreach my $try_server (@{ $spareid{'primary'} },
                    766: 			    @{ $spareid{'default'} }) {
                    767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    768:     }
                    769:     return;
                    770: }
                    771: 
                    772: # -------------------------------- ask if server already has a session for user
                    773: sub has_user_session {
                    774:     my ($lonid,$udom,$uname) = @_;
                    775:     my $result = &reply(join(':','userhassession',
                    776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    777:     return 1 if ($result eq 'ok');
                    778: 
                    779:     return 0;
                    780: }
                    781: 
1.202     matthew   782: # --------------------------------------------- Try to change a user's password
                    783: 
                    784: sub changepass {
1.799     raeburn   785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   786:     $currentpass = &escape($currentpass);
                    787:     $newpass     = &escape($newpass);
1.1030    raeburn   788:     my $lonhost = $perlvar{'lonHostID'};
                    789:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   790: 		       $server);
                    791:     if (! $answer) {
                    792: 	&logthis("No reply on password change request to $server ".
                    793: 		 "by $uname in domain $udom.");
                    794:     } elsif ($answer =~ "^ok") {
                    795:         &logthis("$uname in $udom successfully changed their password ".
                    796: 		 "on $server.");
                    797:     } elsif ($answer =~ "^pwchange_failure") {
                    798: 	&logthis("$uname in $udom was unable to change their password ".
                    799: 		 "on $server.  The action was blocked by either lcpasswd ".
                    800: 		 "or pwchange");
                    801:     } elsif ($answer =~ "^non_authorized") {
                    802:         &logthis("$uname in $udom did not get their password correct when ".
                    803: 		 "attempting to change it on $server.");
                    804:     } elsif ($answer =~ "^auth_mode_error") {
                    805:         &logthis("$uname in $udom attempted to change their password despite ".
                    806: 		 "not being locally or internally authenticated on $server.");
                    807:     } elsif ($answer =~ "^unknown_user") {
                    808:         &logthis("$uname in $udom attempted to change their password ".
                    809: 		 "on $server but were unable to because $server is not ".
                    810: 		 "their home server.");
                    811:     } elsif ($answer =~ "^refused") {
                    812: 	&logthis("$server refused to change $uname in $udom password because ".
                    813: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   814:     } elsif ($answer =~ "invalid_client") {
                    815:         &logthis("$server refused to change $uname in $udom password because ".
                    816:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   817:     }
                    818:     return $answer;
1.1       albertel  819: }
                    820: 
1.169     harris41  821: # ----------------------- Try to determine user's current authentication scheme
                    822: 
                    823: sub queryauthenticate {
                    824:     my ($uname,$udom)=@_;
1.456     albertel  825:     my $uhome=&homeserver($uname,$udom);
                    826:     if (!$uhome) {
                    827: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    828: 	return 'no_host';
                    829:     }
                    830:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    831:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    832: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  833:     }
1.456     albertel  834:     return $answer;
1.169     harris41  835: }
                    836: 
1.1       albertel  837: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       838: 
1.1       albertel  839: sub authenticate {
1.952     raeburn   840:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  841:     $upass=&escape($upass);
                    842:     $uname= &LONCAPA::clean_username($uname);
1.836     www       843:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   844:     my $newhome;
1.836     www       845:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    846: # Maybe the machine was offline and only re-appeared again recently?
                    847:         &reconlonc();
                    848: # One more
1.952     raeburn   849: 	$uhome=&homeserver($uname,$udom,1);
                    850:         if (($uhome eq 'no_host') && $checkdefauth) {
                    851:             if (defined(&domain($udom,'primary'))) {
                    852:                 $newhome=&domain($udom,'primary');
                    853:             }
                    854:             if ($newhome ne '') {
                    855:                 $uhome = $newhome;
                    856:             }
                    857:         }
1.836     www       858: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    859: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   860: 	    return 'no_host';
                    861:         }
1.1       albertel  862:     }
1.952     raeburn   863:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  864:     if ($answer eq 'authorized') {
1.952     raeburn   865:         if ($newhome) {
                    866:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    867:             return 'no_account_on_host'; 
                    868:         } else {
                    869:             &logthis("User $uname at $udom authorized by $uhome");
                    870:             return $uhome;
                    871:         }
1.471     albertel  872:     }
                    873:     if ($answer eq 'non_authorized') {
                    874: 	&logthis("User $uname at $udom rejected by $uhome");
                    875: 	return 'no_host'; 
1.9       www       876:     }
1.471     albertel  877:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  878:     return 'no_host';
                    879: }
                    880: 
                    881: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       882: 
1.599     albertel  883: my %homecache;
1.1       albertel  884: sub homeserver {
1.230     stredwic  885:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  886:     my $index="$uname:$udom";
1.426     albertel  887: 
1.599     albertel  888:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  889: 
                    890:     my %servers = &get_servers($udom,'library');
                    891:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  892:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  893: 		 exists($badServerCache{$tryserver}));
1.841     albertel  894: 
                    895: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    896: 	if ($answer eq 'found') {
                    897: 	    delete($badServerCache{$tryserver}); 
                    898: 	    return $homecache{$index}=$tryserver;
                    899: 	} elsif ($answer eq 'no_host') {
                    900: 	    $badServerCache{$tryserver}=1;
                    901: 	}
1.1       albertel  902:     }    
                    903:     return 'no_host';
1.70      www       904: }
                    905: 
                    906: # ------------------------------------- Find the usernames behind a list of IDs
                    907: 
                    908: sub idget {
                    909:     my ($udom,@ids)=@_;
                    910:     my %returnhash=();
                    911:     
1.841     albertel  912:     my %servers = &get_servers($udom,'library');
                    913:     foreach my $tryserver (keys(%servers)) {
                    914: 	my $idlist=join('&',@ids);
                    915: 	$idlist=~tr/A-Z/a-z/; 
                    916: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    917: 	my @answer=();
                    918: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    919: 	    @answer=split(/\&/,$reply);
                    920: 	}                    ;
                    921: 	my $i;
                    922: 	for ($i=0;$i<=$#ids;$i++) {
                    923: 	    if ($answer[$i]) {
                    924: 		$returnhash{$ids[$i]}=$answer[$i];
                    925: 	    } 
                    926: 	}
                    927:     } 
1.70      www       928:     return %returnhash;
                    929: }
                    930: 
                    931: # ------------------------------------- Find the IDs behind a list of usernames
                    932: 
                    933: sub idrget {
                    934:     my ($udom,@unames)=@_;
                    935:     my %returnhash=();
1.800     albertel  936:     foreach my $uname (@unames) {
                    937:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  938:     }
1.70      www       939:     return %returnhash;
                    940: }
                    941: 
                    942: # ------------------------------- Store away a list of names and associated IDs
                    943: 
                    944: sub idput {
                    945:     my ($udom,%ids)=@_;
                    946:     my %servers=();
1.800     albertel  947:     foreach my $uname (keys(%ids)) {
                    948: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    949:         my $uhom=&homeserver($uname,$udom);
1.70      www       950:         if ($uhom ne 'no_host') {
1.800     albertel  951:             my $id=&escape($ids{$uname});
1.70      www       952:             $id=~tr/A-Z/a-z/;
1.800     albertel  953:             my $esc_unam=&escape($uname);
1.70      www       954: 	    if ($servers{$uhom}) {
1.800     albertel  955: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       956:             } else {
1.800     albertel  957:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       958:             }
                    959:         }
1.191     harris41  960:     }
1.800     albertel  961:     foreach my $server (keys(%servers)) {
                    962:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  963:     }
1.344     www       964: }
                    965: 
1.1023    raeburn   966: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn   967: sub dump_dom {
1.1023    raeburn   968:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn   969:     if (!$udom) {
                    970:         $udom=$env{'user.domain'};
                    971:     }
                    972:     my %returnhash;
1.1023    raeburn   973:     if ($udom) {
                    974:         my $uname = &get_domainconfiguser($udom);
                    975:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn   976:     }
                    977:     return %returnhash;
                    978: }
                    979: 
1.1023    raeburn   980: # ------------------------------------------ get items from domain db files   
1.806     raeburn   981: 
                    982: sub get_dom {
1.860     raeburn   983:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   984:     my $items='';
                    985:     foreach my $item (@$storearr) {
                    986:         $items.=&escape($item).'&';
                    987:     }
                    988:     $items=~s/\&$//;
1.860     raeburn   989:     if (!$udom) {
                    990:         $udom=$env{'user.domain'};
                    991:         if (defined(&domain($udom,'primary'))) {
                    992:             $uhome=&domain($udom,'primary');
                    993:         } else {
1.874     albertel  994:             undef($uhome);
1.860     raeburn   995:         }
                    996:     } else {
                    997:         if (!$uhome) {
                    998:             if (defined(&domain($udom,'primary'))) {
                    999:                 $uhome=&domain($udom,'primary');
                   1000:             }
                   1001:         }
                   1002:     }
                   1003:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1004:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1005:         my %returnhash;
1.875     albertel 1006:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1007:             return %returnhash;
                   1008:         }
1.806     raeburn  1009:         my @pairs=split(/\&/,$rep);
                   1010:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1011:             return @pairs;
                   1012:         }
                   1013:         my $i=0;
                   1014:         foreach my $item (@$storearr) {
                   1015:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1016:             $i++;
                   1017:         }
                   1018:         return %returnhash;
                   1019:     } else {
1.880     banghart 1020:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1021:     }
                   1022: }
                   1023: 
                   1024: # -------------------------------------------- put items in domain db files 
                   1025: 
                   1026: sub put_dom {
1.860     raeburn  1027:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1028:     if (!$udom) {
                   1029:         $udom=$env{'user.domain'};
                   1030:         if (defined(&domain($udom,'primary'))) {
                   1031:             $uhome=&domain($udom,'primary');
                   1032:         } else {
1.874     albertel 1033:             undef($uhome);
1.860     raeburn  1034:         }
                   1035:     } else {
                   1036:         if (!$uhome) {
                   1037:             if (defined(&domain($udom,'primary'))) {
                   1038:                 $uhome=&domain($udom,'primary');
                   1039:             }
                   1040:         }
                   1041:     } 
                   1042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1043:         my $items='';
                   1044:         foreach my $item (keys(%$storehash)) {
                   1045:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1046:         }
                   1047:         $items=~s/\&$//;
                   1048:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1049:     } else {
1.860     raeburn  1050:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1051:     }
                   1052: }
                   1053: 
1.1023    raeburn  1054: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1055: sub newput_dom {
1.1023    raeburn  1056:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1057:     my $result;
                   1058:     if (!$udom) {
                   1059:         $udom=$env{'user.domain'};
                   1060:     }
1.1023    raeburn  1061:     if ($udom) {
                   1062:         my $uname = &get_domainconfiguser($udom);
                   1063:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1064:     }
                   1065:     return $result;
                   1066: }
                   1067: 
1.1023    raeburn  1068: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1069: sub del_dom {
1.1023    raeburn  1070:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1071:     if (ref($storearr) eq 'ARRAY') {
                   1072:         if (!$udom) {
                   1073:             $udom=$env{'user.domain'};
                   1074:         }
1.1023    raeburn  1075:         if ($udom) {
                   1076:             my $uname = &get_domainconfiguser($udom); 
                   1077:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1078:         }
                   1079:     }
                   1080: }
                   1081: 
1.1023    raeburn  1082: # ----------------------------------construct domainconfig user for a domain 
                   1083: sub get_domainconfiguser {
                   1084:     my ($udom) = @_;
                   1085:     return $udom.'-domainconfig';
                   1086: }
                   1087: 
1.837     raeburn  1088: sub retrieve_inst_usertypes {
                   1089:     my ($udom) = @_;
                   1090:     my (%returnhash,@order);
1.989     raeburn  1091:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1092:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1093:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1094:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1095:         @order = @{$domdefs{'inststatusorder'}};
                   1096:     } else {
                   1097:         if (defined(&domain($udom,'primary'))) {
                   1098:             my $uhome=&domain($udom,'primary');
                   1099:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1100:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1101:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1102:                 return (\%returnhash,\@order);
                   1103:             }
                   1104:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1105:             my @pairs=split(/\&/,$hashitems);
                   1106:             foreach my $item (@pairs) {
                   1107:                 my ($key,$value)=split(/=/,$item,2);
                   1108:                 $key = &unescape($key);
                   1109:                 next if ($key =~ /^error: 2 /);
                   1110:                 $returnhash{$key}=&thaw_unescape($value);
                   1111:             }
                   1112:             my @esc_order = split(/\&/,$orderitems);
                   1113:             foreach my $item (@esc_order) {
                   1114:                 push(@order,&unescape($item));
                   1115:             }
                   1116:         } else {
                   1117:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1118:         }
                   1119:     }
                   1120:     return (\%returnhash,\@order);
                   1121: }
                   1122: 
1.868     raeburn  1123: sub is_domainimage {
                   1124:     my ($url) = @_;
                   1125:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1126:         if (&domain($1) ne '') {
                   1127:             return '1';
                   1128:         }
                   1129:     }
                   1130:     return;
                   1131: }
                   1132: 
1.899     raeburn  1133: sub inst_directory_query {
                   1134:     my ($srch) = @_;
                   1135:     my $udom = $srch->{'srchdomain'};
                   1136:     my %results;
                   1137:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1138:     my $outcome;
1.899     raeburn  1139:     if ($homeserver ne '') {
1.904     albertel 1140: 	my $queryid=&reply("querysend:instdirsearch:".
                   1141: 			   &escape($srch->{'srchby'}).':'.
                   1142: 			   &escape($srch->{'srchterm'}).':'.
                   1143: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1144: 	my $host=&hostname($homeserver);
                   1145: 	if ($queryid !~/^\Q$host\E\_/) {
                   1146: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1147: 	    return;
                   1148: 	}
                   1149: 	my $response = &get_query_reply($queryid);
                   1150: 	my $maxtries = 5;
                   1151: 	my $tries = 1;
                   1152: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1153: 	    $response = &get_query_reply($queryid);
                   1154: 	    $tries ++;
                   1155: 	}
                   1156: 
                   1157:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1158:             if ($response eq 'unavailable') {
                   1159:                 $outcome = $response;
                   1160:             } else {
                   1161:                 $outcome = 'ok';
                   1162:                 my @matches = split(/\n/,$response);
                   1163:                 foreach my $match (@matches) {
                   1164:                     my ($key,$value) = split(/=/,$match);
                   1165:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1166:                 }
1.899     raeburn  1167:             }
                   1168:         }
                   1169:     }
1.909     raeburn  1170:     return ($outcome,%results);
1.899     raeburn  1171: }
                   1172: 
                   1173: sub usersearch {
                   1174:     my ($srch) = @_;
                   1175:     my $dom = $srch->{'srchdomain'};
                   1176:     my %results;
                   1177:     my %libserv = &all_library();
                   1178:     my $query = 'usersearch';
                   1179:     foreach my $tryserver (keys(%libserv)) {
                   1180:         if (&host_domain($tryserver) eq $dom) {
                   1181:             my $host=&hostname($tryserver);
                   1182:             my $queryid=
1.911     raeburn  1183:                 &reply("querysend:".&escape($query).':'.
                   1184:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1185:                        &escape($srch->{'srchtype'}).':'.
                   1186:                        &escape($srch->{'srchterm'}),$tryserver);
                   1187:             if ($queryid !~/^\Q$host\E\_/) {
                   1188:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1189:                 next;
1.899     raeburn  1190:             }
                   1191:             my $reply = &get_query_reply($queryid);
                   1192:             my $maxtries = 1;
                   1193:             my $tries = 1;
                   1194:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1195:                 $reply = &get_query_reply($queryid);
                   1196:                 $tries ++;
                   1197:             }
                   1198:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1199:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1200:             } else {
1.911     raeburn  1201:                 my @matches;
                   1202:                 if ($reply =~ /\n/) {
                   1203:                     @matches = split(/\n/,$reply);
                   1204:                 } else {
                   1205:                     @matches = split(/\&/,$reply);
                   1206:                 }
1.899     raeburn  1207:                 foreach my $match (@matches) {
                   1208:                     my ($uname,$udom,%userhash);
1.911     raeburn  1209:                     foreach my $entry (split(/:/,$match)) {
                   1210:                         my ($key,$value) =
                   1211:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1212:                         $userhash{$key} = $value;
                   1213:                         if ($key eq 'username') {
                   1214:                             $uname = $value;
                   1215:                         } elsif ($key eq 'domain') {
                   1216:                             $udom = $value;
1.911     raeburn  1217:                         }
1.899     raeburn  1218:                     }
                   1219:                     $results{$uname.':'.$udom} = \%userhash;
                   1220:                 }
                   1221:             }
                   1222:         }
                   1223:     }
                   1224:     return %results;
                   1225: }
                   1226: 
1.912     raeburn  1227: sub get_instuser {
                   1228:     my ($udom,$uname,$id) = @_;
                   1229:     my $homeserver = &domain($udom,'primary');
                   1230:     my ($outcome,%results);
                   1231:     if ($homeserver ne '') {
                   1232:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1233:                            &escape($id).':'.&escape($udom),$homeserver);
                   1234:         my $host=&hostname($homeserver);
                   1235:         if ($queryid !~/^\Q$host\E\_/) {
                   1236:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1237:             return;
                   1238:         }
                   1239:         my $response = &get_query_reply($queryid);
                   1240:         my $maxtries = 5;
                   1241:         my $tries = 1;
                   1242:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1243:             $response = &get_query_reply($queryid);
                   1244:             $tries ++;
                   1245:         }
                   1246:         if (!&error($response) && $response ne 'refused') {
                   1247:             if ($response eq 'unavailable') {
                   1248:                 $outcome = $response;
                   1249:             } else {
                   1250:                 $outcome = 'ok';
                   1251:                 my @matches = split(/\n/,$response);
                   1252:                 foreach my $match (@matches) {
                   1253:                     my ($key,$value) = split(/=/,$match);
                   1254:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1255:                 }
                   1256:             }
                   1257:         }
                   1258:     }
                   1259:     my %userinfo;
                   1260:     if (ref($results{$uname}) eq 'HASH') {
                   1261:         %userinfo = %{$results{$uname}};
                   1262:     } 
                   1263:     return ($outcome,%userinfo);
                   1264: }
                   1265: 
                   1266: sub inst_rulecheck {
1.923     raeburn  1267:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1268:     my %returnhash;
                   1269:     if ($udom ne '') {
                   1270:         if (ref($rules) eq 'ARRAY') {
                   1271:             @{$rules} = map {&escape($_);} (@{$rules});
                   1272:             my $rulestr = join(':',@{$rules});
                   1273:             my $homeserver=&domain($udom,'primary');
                   1274:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1275:                 my $response;
                   1276:                 if ($item eq 'username') {                
                   1277:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1278:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1279:                                               $homeserver));
1.923     raeburn  1280:                 } elsif ($item eq 'id') {
                   1281:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1282:                                               ':'.&escape($id).':'.$rulestr,
                   1283:                                               $homeserver));
1.945     raeburn  1284:                 } elsif ($item eq 'selfcreate') {
                   1285:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1286:                                                &escape($udom).':'.&escape($uname).
                   1287:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1288:                 }
1.912     raeburn  1289:                 if ($response ne 'refused') {
                   1290:                     my @pairs=split(/\&/,$response);
                   1291:                     foreach my $item (@pairs) {
                   1292:                         my ($key,$value)=split(/=/,$item,2);
                   1293:                         $key = &unescape($key);
                   1294:                         next if ($key =~ /^error: 2 /);
                   1295:                         $returnhash{$key}=&thaw_unescape($value);
                   1296:                     }
                   1297:                 }
                   1298:             }
                   1299:         }
                   1300:     }
                   1301:     return %returnhash;
                   1302: }
                   1303: 
                   1304: sub inst_userrules {
1.923     raeburn  1305:     my ($udom,$check) = @_;
1.912     raeburn  1306:     my (%ruleshash,@ruleorder);
                   1307:     if ($udom ne '') {
                   1308:         my $homeserver=&domain($udom,'primary');
                   1309:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1310:             my $response;
                   1311:             if ($check eq 'id') {
                   1312:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1313:                                  $homeserver);
1.943     raeburn  1314:             } elsif ($check eq 'email') {
                   1315:                 $response=&reply('instemailrules:'.&escape($udom),
                   1316:                                  $homeserver);
1.923     raeburn  1317:             } else {
                   1318:                 $response=&reply('instuserrules:'.&escape($udom),
                   1319:                                  $homeserver);
                   1320:             }
1.912     raeburn  1321:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1322:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1323:                 ($response ne 'no_such_host')) {
                   1324:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1325:                 my @pairs=split(/\&/,$hashitems);
                   1326:                 foreach my $item (@pairs) {
                   1327:                     my ($key,$value)=split(/=/,$item,2);
                   1328:                     $key = &unescape($key);
                   1329:                     next if ($key =~ /^error: 2 /);
                   1330:                     $ruleshash{$key}=&thaw_unescape($value);
                   1331:                 }
                   1332:                 my @esc_order = split(/\&/,$orderitems);
                   1333:                 foreach my $item (@esc_order) {
                   1334:                     push(@ruleorder,&unescape($item));
                   1335:                 }
                   1336:             }
                   1337:         }
                   1338:     }
                   1339:     return (\%ruleshash,\@ruleorder);
                   1340: }
                   1341: 
1.976     raeburn  1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1343: 
                   1344: sub get_domain_defaults {
                   1345:     my ($domain) = @_;
                   1346:     my $cachetime = 60*60*24;
                   1347:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1348:     if (defined($cached)) {
                   1349:         if (ref($result) eq 'HASH') {
                   1350:             return %{$result};
                   1351:         }
                   1352:     }
                   1353:     my %domdefaults;
                   1354:     my %domconfig =
1.989     raeburn  1355:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1356:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1357:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1358:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1359:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1360:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1361:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1362:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1363:     } else {
                   1364:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1365:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1366:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1367:     }
1.976     raeburn  1368:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1369:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1370:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1371:         } else {
                   1372:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1373:         } 
                   1374:         my @usertools = ('aboutme','blog','portfolio');
                   1375:         foreach my $item (@usertools) {
                   1376:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1377:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1378:             }
                   1379:         }
                   1380:     }
1.985     raeburn  1381:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1382:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1383:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1384:         }
                   1385:     }
1.989     raeburn  1386:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1387:         foreach my $item ('inststatustypes','inststatusorder') {
                   1388:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1389:         }
                   1390:     }
1.943     raeburn  1391:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1392:                                   $cachetime);
                   1393:     return %domdefaults;
                   1394: }
                   1395: 
1.344     www      1396: # --------------------------------------------------- Assign a key to a student
                   1397: 
                   1398: sub assign_access_key {
1.364     www      1399: #
                   1400: # a valid key looks like uname:udom#comments
                   1401: # comments are being appended
                   1402: #
1.498     www      1403:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1404:     $kdom=
1.620     albertel 1405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1406:     $knum=
1.620     albertel 1407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1408:     $cdom=
1.620     albertel 1409:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1410:     $cnum=
1.620     albertel 1411:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1412:     $udom=$env{'user.name'} unless (defined($udom));
                   1413:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1414:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1415:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1416:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1417:                                                   # assigned to this person
                   1418:                                                   # - this should not happen,
1.345     www      1419:                                                   # unless something went wrong
                   1420:                                                   # the first time around
                   1421: # ready to assign
1.364     www      1422:         $logentry=$1.'; '.$logentry;
1.496     www      1423:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1424:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1425: # key now belongs to user
1.346     www      1426: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1427:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1428:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1429:                 return 'ok';
                   1430:             } else {
                   1431:                 return 
                   1432:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1433: 	    }
                   1434:         } else {
                   1435:             return 'error: Could not assign key, try again later.';
                   1436:         }
1.364     www      1437:     } elsif (!$existing{$ckey}) {
1.345     www      1438: # the key does not exist
                   1439: 	return 'error: The key does not exist';
                   1440:     } else {
                   1441: # the key is somebody else's
                   1442: 	return 'error: The key is already in use';
                   1443:     }
1.344     www      1444: }
                   1445: 
1.364     www      1446: # ------------------------------------------ put an additional comment on a key
                   1447: 
                   1448: sub comment_access_key {
                   1449: #
                   1450: # a valid key looks like uname:udom#comments
                   1451: # comments are being appended
                   1452: #
                   1453:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1454:     $cdom=
1.620     albertel 1455:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1456:     $cnum=
1.620     albertel 1457:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1458:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1459:     if ($existing{$ckey}) {
                   1460:         $existing{$ckey}.='; '.$logentry;
                   1461: # ready to assign
1.367     www      1462:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1463:                                                  $cdom,$cnum) eq 'ok') {
                   1464: 	    return 'ok';
                   1465:         } else {
                   1466: 	    return 'error: Count not store comment.';
                   1467:         }
                   1468:     } else {
                   1469: # the key does not exist
                   1470: 	return 'error: The key does not exist';
                   1471:     }
                   1472: }
                   1473: 
1.344     www      1474: # ------------------------------------------------------ Generate a set of keys
                   1475: 
                   1476: sub generate_access_keys {
1.364     www      1477:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1478:     $cdom=
1.620     albertel 1479:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1480:     $cnum=
1.620     albertel 1481:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1482:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1483:     unless (($cdom) && ($cnum)) { return 0; }
                   1484:     if ($number>10000) { return 0; }
                   1485:     sleep(2); # make sure don't get same seed twice
                   1486:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1487:     my $total=0;
                   1488:     for (my $i=1;$i<=$number;$i++) {
                   1489:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1490:                   sprintf("%lx",int(100000*rand)).'-'.
                   1491:                   sprintf("%lx",int(100000*rand));
                   1492:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1493:        $newkey=~s/0/h/g; # and also 0 and O
                   1494:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1495:        if ($existing{$newkey}) {
                   1496:            $i--;
                   1497:        } else {
1.364     www      1498: 	  if (&put('accesskeys',
                   1499:               { $newkey => '# generated '.localtime().
1.620     albertel 1500:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1501:                            '; '.$logentry },
                   1502: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1503:               $total++;
                   1504: 	  }
                   1505:        }
                   1506:     }
1.620     albertel 1507:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1508:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1509:     return $total;
                   1510: }
                   1511: 
                   1512: # ------------------------------------------------------- Validate an accesskey
                   1513: 
                   1514: sub validate_access_key {
                   1515:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1516:     $cdom=
1.620     albertel 1517:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1518:     $cnum=
1.620     albertel 1519:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1520:     $udom=$env{'user.domain'} unless (defined($udom));
                   1521:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1522:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1523:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1524: }
                   1525: 
                   1526: # ------------------------------------- Find the section of student in a course
1.652     albertel 1527: sub devalidate_getsection_cache {
                   1528:     my ($udom,$unam,$courseid)=@_;
                   1529:     my $hashid="$udom:$unam:$courseid";
                   1530:     &devalidate_cache_new('getsection',$hashid);
                   1531: }
1.298     matthew  1532: 
1.815     albertel 1533: sub courseid_to_courseurl {
                   1534:     my ($courseid) = @_;
                   1535:     #already url style courseid
                   1536:     return $courseid if ($courseid =~ m{^/});
                   1537: 
                   1538:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1539: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1540: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1541: 	return "/$cdom/$cnum";
                   1542:     }
                   1543: 
                   1544:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1545:     if (exists($courseinfo{'num'})) {
                   1546: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1547:     }
                   1548: 
                   1549:     return undef;
                   1550: }
                   1551: 
1.298     matthew  1552: sub getsection {
                   1553:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1554:     my $cachetime=1800;
1.551     albertel 1555: 
                   1556:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1557:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1558:     if (defined($cached)) { return $result; }
                   1559: 
1.298     matthew  1560:     my %Pending; 
                   1561:     my %Expired;
                   1562:     #
                   1563:     # Each role can either have not started yet (pending), be active, 
                   1564:     #    or have expired.
                   1565:     #
                   1566:     # If there is an active role, we are done.
                   1567:     #
                   1568:     # If there is more than one role which has not started yet, 
                   1569:     #     choose the one which will start sooner
                   1570:     # If there is one role which has not started yet, return it.
                   1571:     #
                   1572:     # If there is more than one expired role, choose the one which ended last.
                   1573:     # If there is a role which has expired, return it.
                   1574:     #
1.815     albertel 1575:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1576:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1577:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1578:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1579:         my $section=$1;
                   1580:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1581:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1582:         my $now=time;
1.548     albertel 1583:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1584:             $Expired{$end}=$section;
                   1585:             next;
                   1586:         }
1.548     albertel 1587:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1588:             $Pending{$start}=$section;
                   1589:             next;
                   1590:         }
1.599     albertel 1591:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1592:     }
                   1593:     #
                   1594:     # Presumedly there will be few matching roles from the above
                   1595:     # loop and the sorting time will be negligible.
                   1596:     if (scalar(keys(%Pending))) {
                   1597:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1598:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1599:     } 
                   1600:     if (scalar(keys(%Expired))) {
                   1601:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1602:         my $time = pop(@sorted);
1.599     albertel 1603:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1604:     }
1.599     albertel 1605:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1606: }
1.70      www      1607: 
1.599     albertel 1608: sub save_cache {
                   1609:     &purge_remembered();
1.722     albertel 1610:     #&Apache::loncommon::validate_page();
1.620     albertel 1611:     undef(%env);
1.780     albertel 1612:     undef($env_loaded);
1.599     albertel 1613: }
1.452     albertel 1614: 
1.599     albertel 1615: my $to_remember=-1;
                   1616: my %remembered;
                   1617: my %accessed;
                   1618: my $kicks=0;
                   1619: my $hits=0;
1.849     albertel 1620: sub make_key {
                   1621:     my ($name,$id) = @_;
1.872     albertel 1622:     if (length($id) > 65 
                   1623: 	&& length(&escape($id)) > 200) {
                   1624: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1625:     }
1.849     albertel 1626:     return &escape($name.':'.$id);
                   1627: }
                   1628: 
1.599     albertel 1629: sub devalidate_cache_new {
                   1630:     my ($name,$id,$debug) = @_;
                   1631:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1632:     $id=&make_key($name,$id);
1.599     albertel 1633:     $memcache->delete($id);
                   1634:     delete($remembered{$id});
                   1635:     delete($accessed{$id});
                   1636: }
                   1637: 
                   1638: sub is_cached_new {
                   1639:     my ($name,$id,$debug) = @_;
1.849     albertel 1640:     $id=&make_key($name,$id);
1.599     albertel 1641:     if (exists($remembered{$id})) {
                   1642: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1643: 	$accessed{$id}=[&gettimeofday()];
                   1644: 	$hits++;
                   1645: 	return ($remembered{$id},1);
                   1646:     }
                   1647:     my $value = $memcache->get($id);
                   1648:     if (!(defined($value))) {
                   1649: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1650: 	return (undef,undef);
1.416     albertel 1651:     }
1.599     albertel 1652:     if ($value eq '__undef__') {
                   1653: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1654: 	$value=undef;
                   1655:     }
                   1656:     &make_room($id,$value,$debug);
                   1657:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1658:     return ($value,1);
                   1659: }
                   1660: 
                   1661: sub do_cache_new {
                   1662:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1663:     $id=&make_key($name,$id);
1.599     albertel 1664:     my $setvalue=$value;
                   1665:     if (!defined($setvalue)) {
                   1666: 	$setvalue='__undef__';
                   1667:     }
1.623     albertel 1668:     if (!defined($time) ) {
                   1669: 	$time=600;
                   1670:     }
1.599     albertel 1671:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1672:     my $result = $memcache->set($id,$setvalue,$time);
                   1673:     if (! $result) {
1.872     albertel 1674: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1675: 	$memcache->disconnect_all();
1.872     albertel 1676:     }
1.600     albertel 1677:     # need to make a copy of $value
1.919     albertel 1678:     &make_room($id,$value,$debug);
1.599     albertel 1679:     return $value;
                   1680: }
                   1681: 
                   1682: sub make_room {
                   1683:     my ($id,$value,$debug)=@_;
1.919     albertel 1684: 
                   1685:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1686:                                     : $value;
1.599     albertel 1687:     if ($to_remember<0) { return; }
                   1688:     $accessed{$id}=[&gettimeofday()];
                   1689:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1690:     my $to_kick;
                   1691:     my $max_time=0;
                   1692:     foreach my $other (keys(%accessed)) {
                   1693: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1694: 	    $to_kick=$other;
                   1695: 	    $max_time=&tv_interval($accessed{$other});
                   1696: 	}
                   1697:     }
                   1698:     delete($remembered{$to_kick});
                   1699:     delete($accessed{$to_kick});
                   1700:     $kicks++;
                   1701:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1702:     return;
                   1703: }
                   1704: 
1.599     albertel 1705: sub purge_remembered {
1.604     albertel 1706:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1707:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1708:     undef(%remembered);
                   1709:     undef(%accessed);
1.428     albertel 1710: }
1.70      www      1711: # ------------------------------------- Read an entry from a user's environment
                   1712: 
                   1713: sub userenvironment {
                   1714:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1715:     my $items;
                   1716:     foreach my $item (@what) {
                   1717:         $items.=&escape($item).'&';
                   1718:     }
                   1719:     $items=~s/\&$//;
1.70      www      1720:     my %returnhash=();
1.1009    raeburn  1721:     my $uhome = &homeserver($unam,$udom);
                   1722:     unless ($uhome eq 'no_host') {
                   1723:         my @answer=split(/\&/, 
                   1724:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
                   1725:         my $i;
                   1726:         for ($i=0;$i<=$#what;$i++) {
                   1727: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1728:         }
1.70      www      1729:     }
                   1730:     return %returnhash;
1.1       albertel 1731: }
                   1732: 
1.617     albertel 1733: # ---------------------------------------------------------- Get a studentphoto
                   1734: sub studentphoto {
                   1735:     my ($udom,$unam,$ext) = @_;
                   1736:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1737:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1738:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1739:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1740:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1741:             } else {
                   1742:                 my ($result,$perm_reqd)=
1.707     albertel 1743: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1744:                 if ($result eq 'ok') {
                   1745:                     if (!($perm_reqd eq 'yes')) {
                   1746:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1747:                     }
                   1748:                 }
                   1749:             }
                   1750:         }
                   1751:     } else {
                   1752:         my ($result,$perm_reqd) = 
1.707     albertel 1753: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1754:         if ($result eq 'ok') {
                   1755:             if (!($perm_reqd eq 'yes')) {
                   1756:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1757:             }
                   1758:         }
                   1759:     }
                   1760:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1761: }
                   1762: 
                   1763: sub retrievestudentphoto {
                   1764:     my ($udom,$unam,$ext,$type) = @_;
                   1765:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1766:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1767:     if ($ret eq 'ok') {
                   1768:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1769:         if ($type eq 'thumbnail') {
                   1770:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1771:         }
                   1772:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1773:         return $tokenurl;
                   1774:     } else {
                   1775:         if ($type eq 'thumbnail') {
                   1776:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1777:         } else { 
                   1778:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1779:         }
1.617     albertel 1780:     }
                   1781: }
                   1782: 
1.263     www      1783: # -------------------------------------------------------------------- New chat
                   1784: 
                   1785: sub chatsend {
1.724     raeburn  1786:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1787:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1788:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1789:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1790:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1791: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1792: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1793: }
                   1794: 
                   1795: # ------------------------------------------ Find current version of a resource
                   1796: 
                   1797: sub getversion {
                   1798:     my $fname=&clutter(shift);
                   1799:     unless ($fname=~/^\/res\//) { return -1; }
                   1800:     return &currentversion(&filelocation('',$fname));
                   1801: }
                   1802: 
                   1803: sub currentversion {
                   1804:     my $fname=shift;
1.599     albertel 1805:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1806:     if (defined($cached)) { return $result; }
1.292     www      1807:     my $author=$fname;
                   1808:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1809:     my ($udom,$uname)=split(/\//,$author);
                   1810:     my $home=homeserver($uname,$udom);
                   1811:     if ($home eq 'no_host') { 
                   1812:         return -1; 
                   1813:     }
                   1814:     my $answer=reply("currentversion:$fname",$home);
                   1815:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1816: 	return -1;
                   1817:     }
1.599     albertel 1818:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1819: }
                   1820: 
1.1       albertel 1821: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1822: 
1.1       albertel 1823: sub subscribe {
                   1824:     my $fname=shift;
1.761     raeburn  1825:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1826:     $fname=~s/[\n\r]//g;
1.1       albertel 1827:     my $author=$fname;
                   1828:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1829:     my ($udom,$uname)=split(/\//,$author);
                   1830:     my $home=homeserver($uname,$udom);
1.335     albertel 1831:     if ($home eq 'no_host') {
                   1832:         return 'not_found';
1.1       albertel 1833:     }
                   1834:     my $answer=reply("sub:$fname",$home);
1.64      www      1835:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1836: 	$answer.=' by '.$home;
                   1837:     }
1.1       albertel 1838:     return $answer;
                   1839: }
                   1840:     
1.8       www      1841: # -------------------------------------------------------------- Replicate file
                   1842: 
                   1843: sub repcopy {
                   1844:     my $filename=shift;
1.23      www      1845:     $filename=~s/\/+/\//g;
1.607     raeburn  1846:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1847:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1848:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1849: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1850: 	return &repcopy_userfile($filename);
                   1851:     }
1.532     albertel 1852:     $filename=~s/[\n\r]//g;
1.8       www      1853:     my $transname="$filename.in.transfer";
1.828     www      1854: # FIXME: this should flock
1.607     raeburn  1855:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1856:     my $remoteurl=subscribe($filename);
1.64      www      1857:     if ($remoteurl =~ /^con_lost by/) {
                   1858: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1859:            return 'unavailable';
1.8       www      1860:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1861: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1862: 	   return 'not_found';
1.64      www      1863:     } elsif ($remoteurl =~ /^rejected by/) {
                   1864: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1865:            return 'forbidden';
1.20      www      1866:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1867:            return 'ok';
1.8       www      1868:     } else {
1.290     www      1869:         my $author=$filename;
                   1870:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1871:         my ($udom,$uname)=split(/\//,$author);
                   1872:         my $home=homeserver($uname,$udom);
                   1873:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1874:            my @parts=split(/\//,$filename);
                   1875:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1876:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1877:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1878: 	       return 'bad_request';
1.8       www      1879:            }
                   1880:            my $count;
                   1881:            for ($count=5;$count<$#parts;$count++) {
                   1882:                $path.="/$parts[$count]";
                   1883:                if ((-e $path)!=1) {
                   1884: 		   mkdir($path,0777);
                   1885:                }
                   1886:            }
                   1887:            my $ua=new LWP::UserAgent;
                   1888:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1889:            my $response=$ua->request($request,$transname);
                   1890:            if ($response->is_error()) {
                   1891: 	       unlink($transname);
                   1892:                my $message=$response->status_line;
1.672     albertel 1893:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1894:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1895:                return 'unavailable';
1.8       www      1896:            } else {
1.16      www      1897: 	       if ($remoteurl!~/\.meta$/) {
                   1898:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1899:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1900:                   if ($mresponse->is_error()) {
                   1901: 		      unlink($filename.'.meta');
                   1902:                       &logthis(
1.672     albertel 1903:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1904:                   }
                   1905: 	       }
1.8       www      1906:                rename($transname,$filename);
1.607     raeburn  1907:                return 'ok';
1.8       www      1908:            }
1.290     www      1909:        }
1.8       www      1910:     }
1.330     www      1911: }
                   1912: 
                   1913: # ------------------------------------------------ Get server side include body
                   1914: sub ssi_body {
1.381     albertel 1915:     my ($filelink,%form)=@_;
1.606     matthew  1916:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1917:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1918:     }
1.953     www      1919:     my $output='';
                   1920:     my $response;
1.980     raeburn  1921:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1922:        ($output,$response)=&externalssi($filelink);
1.953     www      1923:     } else {
1.1004    droeschl 1924:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1925:        $filelink .= 'inhibitmenu=yes';
1.953     www      1926:        ($output,$response)=&ssi($filelink,%form);
                   1927:     }
1.778     albertel 1928:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1929:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1930:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1931:     if (wantarray) {
                   1932:         return ($output, $response);
                   1933:     } else {
                   1934:         return $output;
                   1935:     }
1.8       www      1936: }
                   1937: 
1.15      www      1938: # --------------------------------------------------------- Server Side Include
                   1939: 
1.782     albertel 1940: sub absolute_url {
                   1941:     my ($host_name) = @_;
                   1942:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1943:     if ($host_name eq '') {
                   1944: 	$host_name = $ENV{'SERVER_NAME'};
                   1945:     }
                   1946:     return $protocol.$host_name;
                   1947: }
                   1948: 
1.942     foxr     1949: #
                   1950: #   Server side include.
                   1951: # Parameters:
                   1952: #  fn     Possibly encrypted resource name/id.
                   1953: #  form   Hash that describes how the rendering should be done
                   1954: #         and other things.
1.944     foxr     1955: # Returns:
1.950     raeburn  1956: #   Scalar context: The content of the response.
                   1957: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1958: #     
1.15      www      1959: sub ssi {
                   1960: 
1.944     foxr     1961:     my ($fn,%form)=@_;
1.15      www      1962:     my $ua=new LWP::UserAgent;
1.23      www      1963:     my $request;
1.711     albertel 1964: 
                   1965:     $form{'no_update_last_known'}=1;
1.895     albertel 1966:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1967:     if (%form) {
1.782     albertel 1968:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1969:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1970:     } else {
1.782     albertel 1971:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1972:     }
                   1973: 
1.15      www      1974:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1975:     my $response=$ua->request($request);
                   1976: 
1.944     foxr     1977:     if (wantarray) {
                   1978: 	return ($response->content, $response);
                   1979:     } else {
                   1980: 	return $response->content;
1.942     foxr     1981:     }
1.324     www      1982: }
                   1983: 
                   1984: sub externalssi {
                   1985:     my ($url)=@_;
                   1986:     my $ua=new LWP::UserAgent;
                   1987:     my $request=new HTTP::Request('GET',$url);
                   1988:     my $response=$ua->request($request);
1.954     raeburn  1989:     if (wantarray) {
                   1990:         return ($response->content, $response);
                   1991:     } else {
                   1992:         return $response->content;
                   1993:     }
1.15      www      1994: }
1.254     www      1995: 
1.492     albertel 1996: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1997: 
                   1998: sub allowuploaded {
                   1999:     my ($srcurl,$url)=@_;
                   2000:     $url=&clutter(&declutter($url));
                   2001:     my $dir=$url;
                   2002:     $dir=~s/\/[^\/]+$//;
                   2003:     my %httpref=();
                   2004:     my $httpurl=&hreflocation('',$url);
                   2005:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2006:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2007: }
1.477     raeburn  2008: 
1.478     albertel 2009: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2010: # input: action, courseID, current domain, intended
1.637     raeburn  2011: #        path to file, source of file, instruction to parse file for objects,
                   2012: #        ref to hash for embedded objects,
                   2013: #        ref to hash for codebase of java objects.
                   2014: #
1.485     raeburn  2015: # output: url to file (if action was uploaddoc), 
                   2016: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2017: #
1.478     albertel 2018: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2019: # course.
1.477     raeburn  2020: #
1.478     albertel 2021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2022: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2023: #          course's home server.
1.477     raeburn  2024: #
1.478     albertel 2025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2026: #          be copied from $source (current location) to 
                   2027: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2028: #         and will then be copied to
                   2029: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2030: #         course's home server.
1.485     raeburn  2031: #
1.481     raeburn  2032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2033: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2034: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2035: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2036: #         in course's home server.
1.637     raeburn  2037: #
1.477     raeburn  2038: 
                   2039: sub process_coursefile {
1.638     albertel 2040:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2041:     my $fetchresult;
1.638     albertel 2042:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2043:     if ($action eq 'propagate') {
1.638     albertel 2044:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2045: 			     $home);
1.481     raeburn  2046:     } else {
1.477     raeburn  2047:         my $fpath = '';
                   2048:         my $fname = $file;
1.478     albertel 2049:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2050:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2051:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2052:         if ($action eq 'copy') {
                   2053:             if ($source eq '') {
                   2054:                 $fetchresult = 'no source file';
                   2055:                 return $fetchresult;
                   2056:             } else {
                   2057:                 my $destination = $filepath.'/'.$fname;
                   2058:                 rename($source,$destination);
                   2059:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2060:                                  $home);
1.481     raeburn  2061:             }
                   2062:         } elsif ($action eq 'uploaddoc') {
                   2063:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2064:             print $fh $env{'form.'.$source};
1.481     raeburn  2065:             close($fh);
1.637     raeburn  2066:             if ($parser eq 'parse') {
1.1024    raeburn  2067:                 my $mm = new File::MMagic;
                   2068:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2069:                 if ($mime_type eq 'text/html') {
                   2070:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2071:                     unless ($parse_result eq 'ok') {
                   2072:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2073:                     }
1.637     raeburn  2074:                 }
                   2075:             }
1.477     raeburn  2076:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2077:                                  $home);
1.481     raeburn  2078:             if ($fetchresult eq 'ok') {
                   2079:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2080:             } else {
                   2081:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2082:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2083:                 return '/adm/notfound.html';
                   2084:             }
1.477     raeburn  2085:         }
                   2086:     }
1.485     raeburn  2087:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2088:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2089:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2090:     }
                   2091:     return $fetchresult;
                   2092: }
                   2093: 
1.637     raeburn  2094: sub build_filepath {
                   2095:     my ($fpath) = @_;
                   2096:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2097:     unless ($fpath eq '') {
                   2098:         my @parts=split('/',$fpath);
                   2099:         foreach my $part (@parts) {
                   2100:             $filepath.= '/'.$part;
                   2101:             if ((-e $filepath)!=1) {
                   2102:                 mkdir($filepath,0777);
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return $filepath;
                   2107: }
                   2108: 
                   2109: sub store_edited_file {
1.638     albertel 2110:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2111:     my $file = $primary_url;
                   2112:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2113:     my $fpath = '';
                   2114:     my $fname = $file;
                   2115:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2116:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2117:     my $filepath = &build_filepath($fpath);
                   2118:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2119:     print $fh $content;
                   2120:     close($fh);
1.638     albertel 2121:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2122:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2123: 			  $home);
1.637     raeburn  2124:     if ($$fetchresult eq 'ok') {
                   2125:         return '/uploaded/'.$fpath.'/'.$fname;
                   2126:     } else {
1.638     albertel 2127:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2128: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2129:         return '/adm/notfound.html';
                   2130:     }
                   2131: }
                   2132: 
1.531     albertel 2133: sub clean_filename {
1.831     albertel 2134:     my ($fname,$args)=@_;
1.315     www      2135: # Replace Windows backslashes by forward slashes
1.257     www      2136:     $fname=~s/\\/\//g;
1.831     albertel 2137:     if (!$args->{'keep_path'}) {
                   2138:         # Get rid of everything but the actual filename
                   2139: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2140:     }
1.315     www      2141: # Replace spaces by underscores
                   2142:     $fname=~s/\s+/\_/g;
                   2143: # Replace all other weird characters by nothing
1.831     albertel 2144:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2145: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2146: # numbers
                   2147:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2148:     return $fname;
                   2149: }
1.984     neumanie 2150: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2151: sub resizeImage {
                   2152: 	my($img_url) = @_;	
                   2153: 	my $ima = Image::Magick->new;                       
                   2154:         $ima->Read($img_url);
                   2155: 	if($ima->Get('width') > 400)
                   2156: 	{
                   2157: 		my $factor = $ima->Get('width')/400;
                   2158:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2159: 	}
                   2160: 	if($ima->Get('height') > 500)
                   2161:         {
                   2162:         	my $factor = $ima->Get('height')/500;
                   2163:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2164:         } 
                   2165: 		
                   2166: 	$ima->Write($img_url);
                   2167: }
1.531     albertel 2168: 
1.977     amueller 2169: #Wrapper function for userphotoupload
                   2170: sub userphotoupload
                   2171: {
                   2172: 	my($formname,$subdir) = @_;
                   2173: 	$upload_photo_form = 1;
                   2174: 	return &userfileupload($formname,undef,$subdir);
                   2175: }
                   2176: 
1.608     albertel 2177: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2178: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2179: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2180: #        $coursedoc - if true up to the current course
                   2181: #                     if false
                   2182: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2183: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2184: #        $allfiles - reference to hash for embedded objects
                   2185: #        $codebase - reference to hash for codebase of java objects
                   2186: #        $desuname - username for permanent storage of uploaded file
                   2187: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2188: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2189: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2190: # 
1.686     albertel 2191: # output: url of file in userspace, or error: <message> 
                   2192: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2193: 
                   2194: 
1.531     albertel 2195: sub userfileupload {
1.860     raeburn  2196:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2197:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2198:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2199:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2200:     $fname=&clean_filename($fname);
1.315     www      2201: # See if there is anything left
1.257     www      2202:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2203:     chop($env{'form.'.$formname});
1.523     raeburn  2204:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2205:         my $now = time;
                   2206:         my $filepath = 'tmp/helprequests/'.$now;
                   2207:         my @parts=split(/\//,$filepath);
                   2208:         my $fullpath = $perlvar{'lonDaemons'};
                   2209:         for (my $i=0;$i<@parts;$i++) {
                   2210:             $fullpath .= '/'.$parts[$i];
                   2211:             if ((-e $fullpath)!=1) {
                   2212:                 mkdir($fullpath,0777);
                   2213:             }
                   2214:         }
                   2215:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2216:         print $fh $env{'form.'.$formname};
1.523     raeburn  2217:         close($fh);
1.741     raeburn  2218:         return $fullpath.'/'.$fname;
                   2219:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2220:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2221:                        '_'.$env{'user.domain'}.'/pending';
                   2222:         my @parts=split(/\//,$filepath);
                   2223:         my $fullpath = $perlvar{'lonDaemons'};
                   2224:         for (my $i=0;$i<@parts;$i++) {
                   2225:             $fullpath .= '/'.$parts[$i];
                   2226:             if ((-e $fullpath)!=1) {
                   2227:                 mkdir($fullpath,0777);
                   2228:             }
                   2229:         }
                   2230:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2231:         print $fh $env{'form.'.$formname};
                   2232:         close($fh);
                   2233:         return $fullpath.'/'.$fname;
1.523     raeburn  2234:     }
1.995     raeburn  2235:     if ($subdir eq 'scantron') {
                   2236:         $fname = 'scantron_orig_'.$fname;
                   2237:     } else {   
1.258     www      2238: # Create the directory if not present
1.995     raeburn  2239:         $fname="$subdir/$fname";
                   2240:     }
1.259     www      2241:     if ($coursedoc) {
1.638     albertel 2242: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2243: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2244:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2245:             return &finishuserfileupload($docuname,$docudom,
                   2246: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2247: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2248:         } else {
1.620     albertel 2249:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2250:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2251: 				       $fname,$formname,$parser,
                   2252: 				       $allfiles,$codebase);
1.481     raeburn  2253:         }
1.719     banghart 2254:     } elsif (defined($destuname)) {
                   2255:         my $docuname=$destuname;
                   2256:         my $docudom=$destudom;
1.860     raeburn  2257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2258: 				     $parser,$allfiles,$codebase,
                   2259:                                      $thumbwidth,$thumbheight);
1.719     banghart 2260:         
1.259     www      2261:     } else {
1.638     albertel 2262:         my $docuname=$env{'user.name'};
                   2263:         my $docudom=$env{'user.domain'};
1.714     raeburn  2264:         if (exists($env{'form.group'})) {
                   2265:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2266:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2267:         }
1.860     raeburn  2268: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2269: 				     $parser,$allfiles,$codebase,
                   2270:                                      $thumbwidth,$thumbheight);
1.259     www      2271:     }
1.271     www      2272: }
                   2273: 
                   2274: sub finishuserfileupload {
1.860     raeburn  2275:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2276:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2277:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2278:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2279:   
1.860     raeburn  2280:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2281:     $file=$fname;
                   2282:     if ($fname=~m|/|) {
                   2283:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2284: 	$path.=$fnamepath.'/';
                   2285:     }
1.259     www      2286:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2287:     my $count;
                   2288:     for ($count=4;$count<=$#parts;$count++) {
                   2289:         $filepath.="/$parts[$count]";
                   2290:         if ((-e $filepath)!=1) {
                   2291: 	    mkdir($filepath,0777);
                   2292:         }
                   2293:     }
1.984     neumanie 2294: 
1.258     www      2295: # Save the file
                   2296:     {
1.701     albertel 2297: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2298: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2299: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2300: 	    return '/adm/notfound.html';
                   2301: 	}
                   2302: 	if (!print FH ($env{'form.'.$formname})) {
                   2303: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2304: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2305: 	    return '/adm/notfound.html';
                   2306: 	}
1.570     albertel 2307: 	close(FH);
1.977     amueller 2308: 	if($upload_photo_form==1)
                   2309: 	{
1.984     neumanie 2310: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2311: 		$upload_photo_form = 0;
                   2312: 	}
1.258     www      2313:     }
1.637     raeburn  2314:     if ($parser eq 'parse') {
1.1024    raeburn  2315:         my $mm = new File::MMagic;
                   2316:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2317:         if ($mime_type eq 'text/html') {
                   2318:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2319:                                                        $allfiles,$codebase);
                   2320:             unless ($parse_result eq 'ok') {
                   2321:                 &logthis('Failed to parse '.$filepath.$file.
                   2322: 	   	         ' for embedded media: '.$parse_result); 
                   2323:             }
1.637     raeburn  2324:         }
                   2325:     }
1.860     raeburn  2326:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2327:         my $input = $filepath.'/'.$file;
                   2328:         my $output = $filepath.'/'.'tn-'.$file;
                   2329:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2330:         system("convert -sample $thumbsize $input $output");
                   2331:         if (-e $filepath.'/'.'tn-'.$file) {
                   2332:             $fetchthumb  = 1; 
                   2333:         }
                   2334:     }
1.858     raeburn  2335:  
1.259     www      2336: # Notify homeserver to grep it
                   2337: #
1.984     neumanie 2338:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2339:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2340:     if ($fetchresult eq 'ok') {
1.860     raeburn  2341:         if ($fetchthumb) {
                   2342:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2343:             if ($thumbresult ne 'ok') {
                   2344:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2345:                          $docuhome.': '.$thumbresult);
                   2346:             }
                   2347:         }
1.259     www      2348: #
1.258     www      2349: # Return the URL to it
1.494     albertel 2350:         return '/uploaded/'.$path.$file;
1.263     www      2351:     } else {
1.494     albertel 2352:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2353: 		 ': '.$fetchresult);
1.263     www      2354:         return '/adm/notfound.html';
1.858     raeburn  2355:     }
1.493     albertel 2356: }
                   2357: 
1.637     raeburn  2358: sub extract_embedded_items {
1.961     raeburn  2359:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2360:     my @state = ();
                   2361:     my %javafiles = (
                   2362:                       codebase => '',
                   2363:                       code => '',
                   2364:                       archive => ''
                   2365:                     );
                   2366:     my %mediafiles = (
                   2367:                       src => '',
                   2368:                       movie => '',
                   2369:                      );
1.648     raeburn  2370:     my $p;
                   2371:     if ($content) {
                   2372:         $p = HTML::LCParser->new($content);
                   2373:     } else {
1.961     raeburn  2374:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2375:     }
1.641     albertel 2376:     while (my $t=$p->get_token()) {
1.640     albertel 2377: 	if ($t->[0] eq 'S') {
                   2378: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2379: 	    push(@state, $tagname);
1.648     raeburn  2380:             if (lc($tagname) eq 'allow') {
                   2381:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2382:             }
1.640     albertel 2383: 	    if (lc($tagname) eq 'img') {
                   2384: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2385: 	    }
1.886     albertel 2386: 	    if (lc($tagname) eq 'a') {
                   2387: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2388: 	    }
1.645     raeburn  2389:             if (lc($tagname) eq 'script') {
                   2390:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2391:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2392:                 } else {
                   2393:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2394:                 }
                   2395:             }
                   2396:             if (lc($tagname) eq 'link') {
                   2397:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2398:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2399:                 }
                   2400:             }
1.640     albertel 2401: 	    if (lc($tagname) eq 'object' ||
                   2402: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2403: 		foreach my $item (keys(%javafiles)) {
                   2404: 		    $javafiles{$item} = '';
                   2405: 		}
                   2406: 	    }
                   2407: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2408: 		my $name = lc($attr->{'name'});
                   2409: 		foreach my $item (keys(%javafiles)) {
                   2410: 		    if ($name eq $item) {
                   2411: 			$javafiles{$item} = $attr->{'value'};
                   2412: 			last;
                   2413: 		    }
                   2414: 		}
                   2415: 		foreach my $item (keys(%mediafiles)) {
                   2416: 		    if ($name eq $item) {
                   2417: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2418: 			last;
                   2419: 		    }
                   2420: 		}
                   2421: 	    }
                   2422: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2423: 		foreach my $item (keys(%javafiles)) {
                   2424: 		    if ($attr->{$item}) {
                   2425: 			$javafiles{$item} = $attr->{$item};
                   2426: 			last;
                   2427: 		    }
                   2428: 		}
                   2429: 		foreach my $item (keys(%mediafiles)) {
                   2430: 		    if ($attr->{$item}) {
                   2431: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2432: 			last;
                   2433: 		    }
                   2434: 		}
                   2435: 	    }
                   2436: 	} elsif ($t->[0] eq 'E') {
                   2437: 	    my ($tagname) = ($t->[1]);
                   2438: 	    if ($javafiles{'codebase'} ne '') {
                   2439: 		$javafiles{'codebase'} .= '/';
                   2440: 	    }  
                   2441: 	    if (lc($tagname) eq 'applet' ||
                   2442: 		lc($tagname) eq 'object' ||
                   2443: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2444: 		) {
                   2445: 		foreach my $item (keys(%javafiles)) {
                   2446: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2447: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2448: 			&add_filetype($allfiles,$file,$item);
                   2449: 		    }
                   2450: 		}
                   2451: 	    } 
                   2452: 	    pop @state;
                   2453: 	}
                   2454:     }
1.637     raeburn  2455:     return 'ok';
                   2456: }
                   2457: 
1.639     albertel 2458: sub add_filetype {
                   2459:     my ($allfiles,$file,$type)=@_;
                   2460:     if (exists($allfiles->{$file})) {
                   2461: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2462: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2463: 	}
                   2464:     } else {
                   2465: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2466:     }
                   2467: }
                   2468: 
1.493     albertel 2469: sub removeuploadedurl {
1.984     neumanie 2470:     my ($url)=@_;	
                   2471:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2472:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2473: }
                   2474: 
                   2475: sub removeuserfile {
                   2476:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2477:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2478:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2479:     if ($result eq 'ok') {	
1.798     raeburn  2480:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2481:             my $metafile = $fname.'.meta';
                   2482:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2483: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2484:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2485:             my $sqlresult = 
1.823     albertel 2486:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2487:                                         'portfolio_metadata',$group,
                   2488:                                         'delete');
1.798     raeburn  2489:         }
                   2490:     }
                   2491:     return $result;
1.257     www      2492: }
1.15      www      2493: 
1.530     albertel 2494: sub mkdiruserfile {
                   2495:     my ($docuname,$docudom,$dir)=@_;
                   2496:     my $home=&homeserver($docuname,$docudom);
                   2497:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2498: }
                   2499: 
1.531     albertel 2500: sub renameuserfile {
                   2501:     my ($docuname,$docudom,$old,$new)=@_;
                   2502:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2503:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2504:                         &escape("$old").':'.&escape("$new"),$home);
                   2505:     if ($result eq 'ok') {
                   2506:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2507:             my $oldmeta = $old.'.meta';
                   2508:             my $newmeta = $new.'.meta';
                   2509:             my $metaresult = 
                   2510:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2511: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2512:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2513:             my $sqlresult = 
1.823     albertel 2514:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2515:                                         'portfolio_metadata',$group,
                   2516:                                         'delete');
1.798     raeburn  2517:         }
                   2518:     }
                   2519:     return $result;
1.531     albertel 2520: }
                   2521: 
1.14      www      2522: # ------------------------------------------------------------------------- Log
                   2523: 
                   2524: sub log {
                   2525:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2526:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2527: }
                   2528: 
                   2529: # ------------------------------------------------------------------ Course Log
1.352     www      2530: #
                   2531: # This routine flushes several buffers of non-mission-critical nature
                   2532: #
1.157     www      2533: 
                   2534: sub flushcourselogs {
1.352     www      2535:     &logthis('Flushing log buffers');
                   2536: #
                   2537: # course logs
                   2538: # This is a log of all transactions in a course, which can be used
                   2539: # for data mining purposes
                   2540: #
                   2541: # It also collects the courseid database, which lists last transaction
                   2542: # times and course titles for all courseids
                   2543: #
                   2544:     my %courseidbuffer=();
1.921     raeburn  2545:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2546:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2547: 		          &escape($courselogs{$crsid}),
                   2548: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2549: 	    delete $courselogs{$crsid};
                   2550:         } else {
                   2551:             &logthis('Failed to flush log buffer for '.$crsid);
                   2552:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2553:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2554:                         " exceeded maximum size, deleting.</font>");
                   2555:                delete $courselogs{$crsid};
                   2556:             }
1.352     www      2557:         }
1.920     raeburn  2558:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2559:             'description' => $coursedescrbuf{$crsid},
                   2560:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2561:             'type'        => $coursetypebuf{$crsid},
                   2562:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2563:         };
1.191     harris41 2564:     }
1.352     www      2565: #
                   2566: # Write course id database (reverse lookup) to homeserver of courses 
                   2567: # Is used in pickcourse
                   2568: #
1.840     albertel 2569:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2570:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2571:                                     $courseidbuffer{$crs_home},
                   2572:                                     $crs_home,'timeonly');
1.352     www      2573:     }
                   2574: #
                   2575: # File accesses
                   2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2577: #
1.449     matthew  2578:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2579:         if ($entry =~ /___count$/) {
                   2580:             my ($dom,$name);
1.807     albertel 2581:             ($dom,$name,undef)=
1.811     albertel 2582: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2583:             if (! defined($dom) || $dom eq '' || 
                   2584:                 ! defined($name) || $name eq '') {
1.620     albertel 2585:                 my $cid = $env{'request.course.id'};
                   2586:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2587:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2588:             }
1.450     matthew  2589:             my $value = $accesshash{$entry};
                   2590:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2591:             my %temphash=($url => $value);
1.449     matthew  2592:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2593:             if ($result eq 'ok') {
                   2594:                 delete $accesshash{$entry};
                   2595:             } elsif ($result eq 'unknown_cmd') {
                   2596:                 # Target server has old code running on it.
1.450     matthew  2597:                 my %temphash=($entry => $value);
1.449     matthew  2598:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2599:                     delete $accesshash{$entry};
                   2600:                 }
                   2601:             }
                   2602:         } else {
1.811     albertel 2603:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2604:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2605:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2606:                 delete $accesshash{$entry};
                   2607:             }
1.185     www      2608:         }
1.191     harris41 2609:     }
1.352     www      2610: #
                   2611: # Roles
                   2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2613: #
1.800     albertel 2614:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2615:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2616: 	    split(/\:/,$entry);
                   2617:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2618:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2619:                 $rudom,$runame) eq 'ok') {
                   2620: 	    delete $userrolehash{$entry};
                   2621:         }
                   2622:     }
1.662     raeburn  2623: #
                   2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2625: #
                   2626:     my %domrolebuffer = ();
1.1000    raeburn  2627:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2629:         if ($domrolebuffer{$rudom}) {
                   2630:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2631:                       '='.&escape($domainrolehash{$entry});
                   2632:         } else {
                   2633:             $domrolebuffer{$rudom}.=&escape($entry).
                   2634:                       '='.&escape($domainrolehash{$entry});
                   2635:         }
                   2636:         delete $domainrolehash{$entry};
                   2637:     }
                   2638:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2639: 	my %servers = &get_servers($dom,'library');
                   2640: 	foreach my $tryserver (keys(%servers)) {
                   2641: 	    unless (&reply('domroleput:'.$dom.':'.
                   2642: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2643: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2644: 	    }
1.662     raeburn  2645:         }
                   2646:     }
1.186     www      2647:     $dumpcount++;
1.157     www      2648: }
                   2649: 
                   2650: sub courselog {
                   2651:     my $what=shift;
1.158     www      2652:     $what=time.':'.$what;
1.620     albertel 2653:     unless ($env{'request.course.id'}) { return ''; }
                   2654:     $coursedombuf{$env{'request.course.id'}}=
                   2655:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2656:     $coursenumbuf{$env{'request.course.id'}}=
                   2657:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2658:     $coursehombuf{$env{'request.course.id'}}=
                   2659:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2660:     $coursedescrbuf{$env{'request.course.id'}}=
                   2661:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2662:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2663:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2664:     $courseownerbuf{$env{'request.course.id'}}=
                   2665:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2666:     $coursetypebuf{$env{'request.course.id'}}=
                   2667:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2668:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2669: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2670:     } else {
1.620     albertel 2671: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2672:     }
1.620     albertel 2673:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2674: 	&flushcourselogs();
                   2675:     }
1.158     www      2676: }
                   2677: 
                   2678: sub courseacclog {
                   2679:     my $fnsymb=shift;
1.620     albertel 2680:     unless ($env{'request.course.id'}) { return ''; }
                   2681:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2682:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2683:         $what.=':POST';
1.583     matthew  2684:         # FIXME: Probably ought to escape things....
1.800     albertel 2685: 	foreach my $key (keys(%env)) {
                   2686:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2687:                 my $formitem = $1;
                   2688:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2689:                     $what.=':'.$formitem.'='.$env{$key};
                   2690:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2691:                     $what.=':'.$formitem.'='.$env{$key};
                   2692:                 }
1.158     www      2693:             }
1.191     harris41 2694:         }
1.583     matthew  2695:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2696:         # FIXME: We should not be depending on a form parameter that someone
                   2697:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2698:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2699:             $what.= ':POST';
                   2700:             # FIXME: Probably ought to escape things....
                   2701:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2702:                                  'crsdiscuss') {
1.620     albertel 2703:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2704:             }
                   2705:         }
1.158     www      2706:     }
                   2707:     &courselog($what);
1.149     www      2708: }
                   2709: 
1.185     www      2710: sub countacc {
                   2711:     my $url=&declutter(shift);
1.458     matthew  2712:     return if (! defined($url) || $url eq '');
1.620     albertel 2713:     unless ($env{'request.course.id'}) { return ''; }
                   2714:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2715:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2716:     $accesshash{$key}++;
1.185     www      2717: }
1.349     www      2718: 
1.361     www      2719: sub linklog {
                   2720:     my ($from,$to)=@_;
                   2721:     $from=&declutter($from);
                   2722:     $to=&declutter($to);
                   2723:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2724:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2725: }
                   2726:   
1.349     www      2727: sub userrolelog {
                   2728:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2729:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2730:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2731:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2732:         ($trole=~/^ta/)) {
1.350     www      2733:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2734:        $userrolehash
                   2735:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2736:                     =$tend.':'.$tstart;
1.662     raeburn  2737:     }
1.898     albertel 2738:     if (($env{'request.role'} =~ /dc\./) &&
                   2739: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2740: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2741: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2742:        $userrolehash
                   2743:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2744:                     =$tend.':'.$tstart;
                   2745:     }
1.662     raeburn  2746:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2747:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2748:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2749:         ($trole=~/^sc/)) {
                   2750:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2751:        $domainrolehash
                   2752:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2753:                     = $tend.':'.$tstart;
                   2754:     }
1.351     www      2755: }
                   2756: 
1.957     raeburn  2757: sub courserolelog {
                   2758:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2759:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2760:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2761:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2762:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2763:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2764:             my $cdom = $1;
                   2765:             my $cnum = $2;
                   2766:             my $sec = $3;
                   2767:             my $namespace = 'rolelog';
                   2768:             my %storehash = (
                   2769:                                role    => $trole,
                   2770:                                start   => $tstart,
                   2771:                                end     => $tend,
                   2772:                                selfenroll => $selfenroll,
                   2773:                                context    => $context,
                   2774:                             );
                   2775:             if ($trole eq 'gr') {
                   2776:                 $namespace = 'groupslog';
                   2777:                 $storehash{'group'} = $sec;
                   2778:             } else {
                   2779:                 $storehash{'section'} = $sec;
                   2780:             }
                   2781:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2782:             if (($trole ne 'st') || ($sec ne '')) {
                   2783:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2784:             }
1.957     raeburn  2785:         }
                   2786:     }
                   2787:     return;
                   2788: }
                   2789: 
1.351     www      2790: sub get_course_adv_roles {
1.948     raeburn  2791:     my ($cid,$codes) = @_;
1.620     albertel 2792:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2793:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2794:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2795:     my %nothide=();
1.800     albertel 2796:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2797:         if ($user !~ /:/) {
                   2798: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2799:         } else {
                   2800:             $nothide{$user}=1;
                   2801:         }
1.470     www      2802:     }
1.351     www      2803:     my %returnhash=();
                   2804:     my %dumphash=
                   2805:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2806:     my $now=time;
1.997     raeburn  2807:     my %privileged;
1.1000    raeburn  2808:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2809: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2810:         if (($tstart) && ($tstart<0)) { next; }
                   2811:         if (($tend) && ($tend<$now)) { next; }
                   2812:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2813:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2814: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2815:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2816:             my %dompersonnel =
1.998     raeburn  2817:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2818:             $privileged{$domain} = {};
                   2819:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2820:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2821:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2822:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2823:                         $privileged{$udom}{$uname} = 1;
                   2824:                     }
                   2825:                 }
                   2826:             }
                   2827:         }
                   2828:         if ((exists($privileged{$domain}{$username})) && 
                   2829:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2830: 	if ($role eq 'cr') { next; }
1.948     raeburn  2831:         if ($codes) {
                   2832:             if ($section) { $role .= ':'.$section; }
                   2833:             if ($returnhash{$role}) {
                   2834:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2835:             } else {
                   2836:                 $returnhash{$role}=$username.':'.$domain;
                   2837:             }
1.351     www      2838:         } else {
1.988     raeburn  2839:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2840:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2841:             if ($returnhash{$key}) {
                   2842: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2843:             } else {
                   2844:                 $returnhash{$key}=$username.':'.$domain;
                   2845:             }
1.351     www      2846:         }
1.948     raeburn  2847:     }
1.400     www      2848:     return %returnhash;
                   2849: }
                   2850: 
                   2851: sub get_my_roles {
1.937     raeburn  2852:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2853:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2854:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2855:     my (%dumphash,%nothide);
1.858     raeburn  2856:     if ($context eq 'userroles') { 
                   2857:         %dumphash = &dump('roles',$udom,$uname);
                   2858:     } else {
                   2859:         %dumphash=
1.400     www      2860:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2861:         if ($hidepriv) {
                   2862:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2863:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2864:                 if ($user !~ /:/) {
                   2865:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2866:                 } else {
                   2867:                     $nothide{$user} = 1;
                   2868:                 }
                   2869:             }
                   2870:         }
1.858     raeburn  2871:     }
1.400     www      2872:     my %returnhash=();
                   2873:     my $now=time;
1.999     raeburn  2874:     my %privileged;
1.800     albertel 2875:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2876:         my ($role,$tend,$tstart);
                   2877:         if ($context eq 'userroles') {
                   2878: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2879:         } else {
                   2880:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2881:         }
1.400     www      2882:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2883:         my $status = 'active';
1.939     raeburn  2884:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2885:             $status = 'previous';
                   2886:         } 
                   2887:         if (($tstart) && ($now<$tstart)) {
                   2888:             $status = 'future';
                   2889:         }
                   2890:         if (ref($types) eq 'ARRAY') {
                   2891:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2892:                 next;
                   2893:             } 
                   2894:         } else {
                   2895:             if ($status ne 'active') {
                   2896:                 next;
                   2897:             }
                   2898:         }
1.867     raeburn  2899:         my ($rolecode,$username,$domain,$section,$area);
                   2900:         if ($context eq 'userroles') {
                   2901:             ($area,$rolecode) = split(/_/,$entry);
                   2902:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2903:         } else {
                   2904:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2905:         }
1.832     raeburn  2906:         if (ref($roledoms) eq 'ARRAY') {
                   2907:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2908:                 next;
                   2909:             }
                   2910:         }
                   2911:         if (ref($roles) eq 'ARRAY') {
                   2912:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2913:                 if ($role =~ /^cr\//) {
                   2914:                     if (!grep(/^cr$/,@{$roles})) {
                   2915:                         next;
                   2916:                     }
                   2917:                 } else {
                   2918:                     next;
                   2919:                 }
1.832     raeburn  2920:             }
1.867     raeburn  2921:         }
1.937     raeburn  2922:         if ($hidepriv) {
1.999     raeburn  2923:             if ($context eq 'userroles') {
                   2924:                 if ((&privileged($username,$domain)) &&
                   2925:                     (!$nothide{$username.':'.$domain})) {
                   2926:                     next;
                   2927:                 }
                   2928:             } else {
                   2929:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2930:                     my %dompersonnel =
                   2931:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2932:                     $privileged{$domain} = {};
                   2933:                     if (keys(%dompersonnel)) {
                   2934:                         foreach my $server (keys(%dompersonnel)) {
                   2935:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2936:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2937:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2938:                                     $privileged{$udom}{$uname} = $trole;
                   2939:                                 }
                   2940:                             }
                   2941:                         }
                   2942:                     }
                   2943:                 }
                   2944:                 if (exists($privileged{$domain}{$username})) {
                   2945:                     if (!$nothide{$username.':'.$domain}) {
                   2946:                         next;
                   2947:                     }
                   2948:                 }
1.937     raeburn  2949:             }
                   2950:         }
1.933     raeburn  2951:         if ($withsec) {
                   2952:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2953:                 $tstart.':'.$tend;
                   2954:         } else {
                   2955:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2956:         }
1.832     raeburn  2957:     }
1.373     www      2958:     return %returnhash;
1.399     www      2959: }
                   2960: 
                   2961: # ----------------------------------------------------- Frontpage Announcements
                   2962: #
                   2963: #
                   2964: 
                   2965: sub postannounce {
                   2966:     my ($server,$text)=@_;
1.844     albertel 2967:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2968:     unless ($text=~/\w/) { $text=''; }
                   2969:     return &reply('setannounce:'.&escape($text),$server);
                   2970: }
                   2971: 
                   2972: sub getannounce {
1.448     albertel 2973: 
                   2974:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2975: 	my $announcement='';
1.800     albertel 2976: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2977: 	close($fh);
1.399     www      2978: 	if ($announcement=~/\w/) { 
                   2979: 	    return 
                   2980:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2981:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2982: 	} else {
                   2983: 	    return '';
                   2984: 	}
                   2985:     } else {
                   2986: 	return '';
                   2987:     }
1.351     www      2988: }
1.353     www      2989: 
                   2990: # ---------------------------------------------------------- Course ID routines
                   2991: # Deal with domain's nohist_courseid.db files
                   2992: #
                   2993: 
                   2994: sub courseidput {
1.921     raeburn  2995:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2996:     my $outcome;
                   2997:     if ($caller eq 'timeonly') {
                   2998:         my $cids = '';
                   2999:         foreach my $item (keys(%$storehash)) {
                   3000:             $cids.=&escape($item).'&';
                   3001:         }
                   3002:         $cids=~s/\&$//;
                   3003:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3004:                           $coursehome);       
                   3005:     } else {
                   3006:         my $items = '';
                   3007:         foreach my $item (keys(%$storehash)) {
                   3008:             $items.= &escape($item).'='.
                   3009:                      &freeze_escape($$storehash{$item}).'&';
                   3010:         }
                   3011:         $items=~s/\&$//;
                   3012:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3013:                           $coursehome);
1.918     raeburn  3014:     }
                   3015:     if ($outcome eq 'unknown_cmd') {
                   3016:         my $what;
                   3017:         foreach my $cid (keys(%$storehash)) {
                   3018:             $what .= &escape($cid).'=';
1.921     raeburn  3019:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3020:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3021:             }
                   3022:             $what =~ s/\:$/&/;
                   3023:         }
                   3024:         $what =~ s/\&$//;  
                   3025:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3026:     } else {
                   3027:         return $outcome;
                   3028:     }
1.353     www      3029: }
                   3030: 
                   3031: sub courseiddump {
1.921     raeburn  3032:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3033:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3034:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
                   3035:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918     raeburn  3036:     my $as_hash = 1;
                   3037:     my %returnhash;
                   3038:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3039:     my %libserv = &all_library();
                   3040:     foreach my $tryserver (keys(%libserv)) {
                   3041:         if ( (  $hostidflag == 1 
                   3042: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3043: 	     || (!defined($hostidflag)) ) {
                   3044: 
1.918     raeburn  3045: 	    if (($domfilter eq '') ||
                   3046: 		(&host_domain($tryserver) eq $domfilter)) {
                   3047:                 my $rep = 
                   3048:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3049:                          $sincefilter.':'.&escape($descfilter).':'.
                   3050:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3051:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3052:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3053:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3054:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3055:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3056:                          &escape($createdbefore).':'.&escape($createdafter).':'.
                   3057:                          &escape($creationcontext),$tryserver);
1.918     raeburn  3058:                 my @pairs=split(/\&/,$rep);
                   3059:                 foreach my $item (@pairs) {
                   3060:                     my ($key,$value)=split(/\=/,$item,2);
                   3061:                     $key = &unescape($key);
                   3062:                     next if ($key =~ /^error: 2 /);
                   3063:                     my $result = &thaw_unescape($value);
                   3064:                     if (ref($result) eq 'HASH') {
                   3065:                         $returnhash{$key}=$result;
                   3066:                     } else {
1.921     raeburn  3067:                         my @responses = split(/:/,$value);
                   3068:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3069:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3070:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3071:                         }
1.1008    raeburn  3072:                     }
1.353     www      3073:                 }
                   3074:             }
                   3075:         }
                   3076:     }
                   3077:     return %returnhash;
                   3078: }
                   3079: 
1.658     raeburn  3080: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3081: 
                   3082: sub dcmailput {
1.685     raeburn  3083:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3084:     my $status = &Apache::lonnet::critical(
1.740     www      3085:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3086:        &escape($message),$server);
1.662     raeburn  3087:     return $status;
                   3088: }
                   3089: 
1.658     raeburn  3090: sub dcmaildump {
                   3091:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3092:     my %returnhash=();
1.846     albertel 3093: 
                   3094:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3095:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3096:                                                          &escape($enddate).':';
                   3097: 	my @esc_senders=map { &escape($_)} @$senders;
                   3098: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3099: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3100:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3101:             if (($key) && ($value)) {
                   3102:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3103:             }
                   3104:         }
                   3105:     }
                   3106:     return %returnhash;
                   3107: }
1.662     raeburn  3108: # ---------------------------------------------------------- Domain roles
                   3109: 
                   3110: sub get_domain_roles {
                   3111:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3112:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3113:         $startdate = '.';
                   3114:     }
1.1018    raeburn  3115:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3116:         $enddate = '.';
                   3117:     }
1.922     raeburn  3118:     my $rolelist;
                   3119:     if (ref($roles) eq 'ARRAY') {
                   3120:         $rolelist = join(':',@{$roles});
                   3121:     }
1.662     raeburn  3122:     my %personnel = ();
1.841     albertel 3123: 
                   3124:     my %servers = &get_servers($dom,'library');
                   3125:     foreach my $tryserver (keys(%servers)) {
                   3126: 	%{$personnel{$tryserver}}=();
                   3127: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3128: 					    &escape($startdate).':'.
                   3129: 					    &escape($enddate).':'.
                   3130: 					    &escape($rolelist), $tryserver))) {
                   3131: 	    my ($key,$value) = split(/\=/,$line,2);
                   3132: 	    if (($key) && ($value)) {
                   3133: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3134: 	    }
                   3135: 	}
1.662     raeburn  3136:     }
                   3137:     return %personnel;
                   3138: }
1.658     raeburn  3139: 
1.149     www      3140: # ----------------------------------------------------------- Check out an item
                   3141: 
1.504     albertel 3142: sub get_first_access {
                   3143:     my ($type,$argsymb)=@_;
1.790     albertel 3144:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3145:     if ($argsymb) { $symb=$argsymb; }
                   3146:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3147:     if ($type eq 'course') {
                   3148: 	$res='course';
                   3149:     } elsif ($type eq 'map') {
1.588     albertel 3150: 	$res=&symbread($map);
                   3151:     } else {
                   3152: 	$res=$symb;
                   3153:     }
                   3154:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3155:     return $times{"$courseid\0$res"};
1.504     albertel 3156: }
                   3157: 
                   3158: sub set_first_access {
                   3159:     my ($type)=@_;
1.790     albertel 3160:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3161:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3162:     if ($type eq 'course') {
                   3163: 	$res='course';
                   3164:     } elsif ($type eq 'map') {
1.588     albertel 3165: 	$res=&symbread($map);
                   3166:     } else {
                   3167: 	$res=$symb;
                   3168:     }
                   3169:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3170:     if (!$firstaccess) {
1.588     albertel 3171: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3172:     }
                   3173:     return 'already_set';
1.504     albertel 3174: }
                   3175: 
1.149     www      3176: sub checkout {
                   3177:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3178:     my $now=time;
                   3179:     my $lonhost=$perlvar{'lonHostID'};
                   3180:     my $infostr=&escape(
1.234     www      3181:                  'CHECKOUTTOKEN&'.
1.149     www      3182:                  $tuname.'&'.
                   3183:                  $tudom.'&'.
                   3184:                  $tcrsid.'&'.
                   3185:                  $symb.'&'.
                   3186: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3187:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3188:     if ($token=~/^error\:/) { 
1.672     albertel 3189:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3190:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3191:                  "</font>");
                   3192:         return ''; 
                   3193:     }
                   3194: 
1.149     www      3195:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3196:     $token=~tr/a-z/A-Z/;
                   3197: 
1.153     www      3198:     my %infohash=('resource.0.outtoken' => $token,
                   3199:                   'resource.0.checkouttime' => $now,
                   3200:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3201: 
                   3202:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3203:        return '';
1.151     www      3204:     } else {
1.672     albertel 3205:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3206:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3207:                  "</font>");
1.149     www      3208:     }    
                   3209: 
                   3210:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3211:                          &escape('Checkout '.$infostr.' - '.
                   3212:                                                  $token)) ne 'ok') {
                   3213: 	return '';
1.151     www      3214:     } else {
1.672     albertel 3215:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3216:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3217:                  "</font>");
1.149     www      3218:     }
1.151     www      3219:     return $token;
1.149     www      3220: }
                   3221: 
                   3222: # ------------------------------------------------------------ Check in an item
                   3223: 
                   3224: sub checkin {
                   3225:     my $token=shift;
1.150     www      3226:     my $now=time;
                   3227:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3228:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3229:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3230:     $dtoken=~s/\W/\_/g;
1.234     www      3231:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3232:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3233: 
1.154     www      3234:     unless (($tuname) && ($tudom)) {
                   3235:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3236:         return '';
                   3237:     }
                   3238:     
                   3239:     unless (&allowed('mgr',$tcrsid)) {
                   3240:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3241:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3242:         return '';
                   3243:     }
                   3244: 
1.153     www      3245:     my %infohash=('resource.0.intoken' => $token,
                   3246:                   'resource.0.checkintime' => $now,
                   3247:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3248: 
                   3249:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3250:        return '';
                   3251:     }    
                   3252: 
                   3253:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3254:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3255: 	return '';
                   3256:     }
                   3257: 
                   3258:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3259: }
                   3260: 
                   3261: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3262: 
                   3263: sub expirespread {
                   3264:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3265:     my $cid=$env{'request.course.id'}; 
1.110     www      3266:     if ($cid) {
                   3267:        my $now=time;
                   3268:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3269:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3270:                             $env{'course.'.$cid.'.num'}.
1.110     www      3271: 	        	    ':nohist_expirationdates:'.
                   3272:                             &escape($key).'='.$now,
1.620     albertel 3273:                             $env{'course.'.$cid.'.home'})
1.110     www      3274:     }
                   3275:     return 'ok';
1.14      www      3276: }
                   3277: 
1.109     www      3278: # ----------------------------------------------------- Devalidate Spreadsheets
                   3279: 
                   3280: sub devalidate {
1.325     www      3281:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3282:     my $cid=$env{'request.course.id'}; 
1.109     www      3283:     if ($cid) {
1.391     matthew  3284:         # delete the stored spreadsheets for
                   3285:         # - the student level sheet of this user in course's homespace
                   3286:         # - the assessment level sheet for this resource 
                   3287:         #   for this user in user's homespace
1.553     albertel 3288: 	# - current conditional state info
1.325     www      3289: 	my $key=$uname.':'.$udom.':';
1.109     www      3290:         my $status=
1.299     matthew  3291: 	    &del('nohist_calculatedsheets',
1.391     matthew  3292: 		 [$key.'studentcalc:'],
1.620     albertel 3293: 		 $env{'course.'.$cid.'.domain'},
                   3294: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3295: 		.' '.
                   3296: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3297: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3298:         unless ($status eq 'ok ok') {
                   3299:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3300:                     $uname.' at '.$udom.' for '.
1.109     www      3301: 		    $symb.': '.$status);
1.133     albertel 3302:         }
1.553     albertel 3303: 	&delenv('user.state.'.$cid);
1.109     www      3304:     }
                   3305: }
                   3306: 
1.265     albertel 3307: sub get_scalar {
                   3308:     my ($string,$end) = @_;
                   3309:     my $value;
                   3310:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3311: 	$value = $1;
                   3312:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3313: 	$value = $1;
                   3314:     }
                   3315:     return &unescape($value);
                   3316: }
                   3317: 
                   3318: sub array2str {
                   3319:   my (@array) = @_;
                   3320:   my $result=&arrayref2str(\@array);
                   3321:   $result=~s/^__ARRAY_REF__//;
                   3322:   $result=~s/__END_ARRAY_REF__$//;
                   3323:   return $result;
                   3324: }
                   3325: 
1.204     albertel 3326: sub arrayref2str {
                   3327:   my ($arrayref) = @_;
1.265     albertel 3328:   my $result='__ARRAY_REF__';
1.204     albertel 3329:   foreach my $elem (@$arrayref) {
1.265     albertel 3330:     if(ref($elem) eq 'ARRAY') {
                   3331:       $result.=&arrayref2str($elem).'&';
                   3332:     } elsif(ref($elem) eq 'HASH') {
                   3333:       $result.=&hashref2str($elem).'&';
                   3334:     } elsif(ref($elem)) {
                   3335:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3336:     } else {
                   3337:       $result.=&escape($elem).'&';
                   3338:     }
                   3339:   }
                   3340:   $result=~s/\&$//;
1.265     albertel 3341:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3342:   return $result;
                   3343: }
                   3344: 
1.168     albertel 3345: sub hash2str {
1.204     albertel 3346:   my (%hash) = @_;
                   3347:   my $result=&hashref2str(\%hash);
1.265     albertel 3348:   $result=~s/^__HASH_REF__//;
                   3349:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3350:   return $result;
                   3351: }
                   3352: 
                   3353: sub hashref2str {
                   3354:   my ($hashref)=@_;
1.265     albertel 3355:   my $result='__HASH_REF__';
1.800     albertel 3356:   foreach my $key (sort(keys(%$hashref))) {
                   3357:     if (ref($key) eq 'ARRAY') {
                   3358:       $result.=&arrayref2str($key).'=';
                   3359:     } elsif (ref($key) eq 'HASH') {
                   3360:       $result.=&hashref2str($key).'=';
                   3361:     } elsif (ref($key)) {
1.265     albertel 3362:       $result.='=';
1.800     albertel 3363:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3364:     } else {
1.800     albertel 3365: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3366:     }
                   3367: 
1.800     albertel 3368:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3369:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3370:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3371:       $result.=&hashref2str($hashref->{$key}).'&';
                   3372:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3373:        $result.='&';
1.800     albertel 3374:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3375:     } else {
1.800     albertel 3376:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3377:     }
                   3378:   }
1.168     albertel 3379:   $result=~s/\&$//;
1.265     albertel 3380:   $result .= '__END_HASH_REF__';
1.168     albertel 3381:   return $result;
                   3382: }
                   3383: 
                   3384: sub str2hash {
1.265     albertel 3385:     my ($string)=@_;
                   3386:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3387:     return %$hash;
                   3388: }
                   3389: 
                   3390: sub str2hashref {
1.168     albertel 3391:   my ($string) = @_;
1.265     albertel 3392: 
                   3393:   my %hash;
                   3394: 
                   3395:   if($string !~ /^__HASH_REF__/) {
                   3396:       if (! ($string eq '' || !defined($string))) {
                   3397: 	  $hash{'error'}='Not hash reference';
                   3398:       }
                   3399:       return (\%hash, $string);
                   3400:   }
                   3401: 
                   3402:   $string =~ s/^__HASH_REF__//;
                   3403: 
                   3404:   while($string !~ /^__END_HASH_REF__/) {
                   3405:       #key
                   3406:       my $key='';
                   3407:       if($string =~ /^__HASH_REF__/) {
                   3408:           ($key, $string)=&str2hashref($string);
                   3409:           if(defined($key->{'error'})) {
                   3410:               $hash{'error'}='Bad data';
                   3411:               return (\%hash, $string);
                   3412:           }
                   3413:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3414:           ($key, $string)=&str2arrayref($string);
                   3415:           if($key->[0] eq 'Array reference error') {
                   3416:               $hash{'error'}='Bad data';
                   3417:               return (\%hash, $string);
                   3418:           }
                   3419:       } else {
                   3420:           $string =~ s/^(.*?)=//;
1.267     albertel 3421: 	  $key=&unescape($1);
1.265     albertel 3422:       }
                   3423:       $string =~ s/^=//;
                   3424: 
                   3425:       #value
                   3426:       my $value='';
                   3427:       if($string =~ /^__HASH_REF__/) {
                   3428:           ($value, $string)=&str2hashref($string);
                   3429:           if(defined($value->{'error'})) {
                   3430:               $hash{'error'}='Bad data';
                   3431:               return (\%hash, $string);
                   3432:           }
                   3433:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3434:           ($value, $string)=&str2arrayref($string);
                   3435:           if($value->[0] eq 'Array reference error') {
                   3436:               $hash{'error'}='Bad data';
                   3437:               return (\%hash, $string);
                   3438:           }
                   3439:       } else {
                   3440: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3441:       }
                   3442:       $string =~ s/^&//;
                   3443: 
                   3444:       $hash{$key}=$value;
1.204     albertel 3445:   }
1.265     albertel 3446: 
                   3447:   $string =~ s/^__END_HASH_REF__//;
                   3448: 
                   3449:   return (\%hash, $string);
1.204     albertel 3450: }
                   3451: 
                   3452: sub str2array {
1.265     albertel 3453:     my ($string)=@_;
                   3454:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3455:     return @$array;
                   3456: }
                   3457: 
                   3458: sub str2arrayref {
1.204     albertel 3459:   my ($string) = @_;
1.265     albertel 3460:   my @array;
                   3461: 
                   3462:   if($string !~ /^__ARRAY_REF__/) {
                   3463:       if (! ($string eq '' || !defined($string))) {
                   3464: 	  $array[0]='Array reference error';
                   3465:       }
                   3466:       return (\@array, $string);
                   3467:   }
                   3468: 
                   3469:   $string =~ s/^__ARRAY_REF__//;
                   3470: 
                   3471:   while($string !~ /^__END_ARRAY_REF__/) {
                   3472:       my $value='';
                   3473:       if($string =~ /^__HASH_REF__/) {
                   3474:           ($value, $string)=&str2hashref($string);
                   3475:           if(defined($value->{'error'})) {
                   3476:               $array[0] ='Array reference error';
                   3477:               return (\@array, $string);
                   3478:           }
                   3479:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3480:           ($value, $string)=&str2arrayref($string);
                   3481:           if($value->[0] eq 'Array reference error') {
                   3482:               $array[0] ='Array reference error';
                   3483:               return (\@array, $string);
                   3484:           }
                   3485:       } else {
                   3486: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3487:       }
                   3488:       $string =~ s/^&//;
                   3489: 
                   3490:       push(@array, $value);
1.191     harris41 3491:   }
1.265     albertel 3492: 
                   3493:   $string =~ s/^__END_ARRAY_REF__//;
                   3494: 
                   3495:   return (\@array, $string);
1.168     albertel 3496: }
                   3497: 
1.167     albertel 3498: # -------------------------------------------------------------------Temp Store
                   3499: 
1.168     albertel 3500: sub tmpreset {
                   3501:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3502:   if (!$symb) {
                   3503:     $symb=&symbread();
1.620     albertel 3504:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3505:   }
                   3506:   $symb=escape($symb);
                   3507: 
1.620     albertel 3508:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3509:   $namespace=~s/\//\_/g;
                   3510:   $namespace=~s/\W//g;
                   3511: 
1.620     albertel 3512:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3513:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3514:   if ($domain eq 'public' && $stuname eq 'public') {
                   3515:       $stuname=$ENV{'REMOTE_ADDR'};
                   3516:   }
1.168     albertel 3517:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3518:   my %hash;
                   3519:   if (tie(%hash,'GDBM_File',
                   3520: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3521: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3522:     foreach my $key (keys(%hash)) {
1.180     albertel 3523:       if ($key=~ /:$symb/) {
1.168     albertel 3524: 	delete($hash{$key});
                   3525:       }
                   3526:     }
                   3527:   }
                   3528: }
                   3529: 
1.167     albertel 3530: sub tmpstore {
1.168     albertel 3531:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3532: 
                   3533:   if (!$symb) {
                   3534:     $symb=&symbread();
1.620     albertel 3535:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3536:   }
                   3537:   $symb=escape($symb);
                   3538: 
                   3539:   if (!$namespace) {
                   3540:     # I don't think we would ever want to store this for a course.
                   3541:     # it seems this will only be used if we don't have a course.
1.620     albertel 3542:     #$namespace=$env{'request.course.id'};
1.168     albertel 3543:     #if (!$namespace) {
1.620     albertel 3544:       $namespace=$env{'request.state'};
1.168     albertel 3545:     #}
                   3546:   }
                   3547:   $namespace=~s/\//\_/g;
                   3548:   $namespace=~s/\W//g;
1.620     albertel 3549:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3550:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3551:   if ($domain eq 'public' && $stuname eq 'public') {
                   3552:       $stuname=$ENV{'REMOTE_ADDR'};
                   3553:   }
1.168     albertel 3554:   my $now=time;
                   3555:   my %hash;
                   3556:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3557:   if (tie(%hash,'GDBM_File',
                   3558: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3559: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3560:     $hash{"version:$symb"}++;
                   3561:     my $version=$hash{"version:$symb"};
                   3562:     my $allkeys=''; 
                   3563:     foreach my $key (keys(%$storehash)) {
                   3564:       $allkeys.=$key.':';
1.591     albertel 3565:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3566:     }
                   3567:     $hash{"$version:$symb:timestamp"}=$now;
                   3568:     $allkeys.='timestamp';
                   3569:     $hash{"$version:keys:$symb"}=$allkeys;
                   3570:     if (untie(%hash)) {
                   3571:       return 'ok';
                   3572:     } else {
                   3573:       return "error:$!";
                   3574:     }
                   3575:   } else {
                   3576:     return "error:$!";
                   3577:   }
                   3578: }
1.167     albertel 3579: 
1.168     albertel 3580: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3581: 
1.168     albertel 3582: sub tmprestore {
                   3583:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3584: 
1.168     albertel 3585:   if (!$symb) {
                   3586:     $symb=&symbread();
1.620     albertel 3587:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3588:   }
                   3589:   $symb=escape($symb);
                   3590: 
1.620     albertel 3591:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3592: 
1.620     albertel 3593:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3594:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3595:   if ($domain eq 'public' && $stuname eq 'public') {
                   3596:       $stuname=$ENV{'REMOTE_ADDR'};
                   3597:   }
1.168     albertel 3598:   my %returnhash;
                   3599:   $namespace=~s/\//\_/g;
                   3600:   $namespace=~s/\W//g;
                   3601:   my %hash;
                   3602:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3603:   if (tie(%hash,'GDBM_File',
                   3604: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3605: 	  &GDBM_READER(),0640)) {
1.168     albertel 3606:     my $version=$hash{"version:$symb"};
                   3607:     $returnhash{'version'}=$version;
                   3608:     my $scope;
                   3609:     for ($scope=1;$scope<=$version;$scope++) {
                   3610:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3611:       my @keys=split(/:/,$vkeys);
                   3612:       my $key;
                   3613:       $returnhash{"$scope:keys"}=$vkeys;
                   3614:       foreach $key (@keys) {
1.591     albertel 3615: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3616: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3617:       }
                   3618:     }
1.168     albertel 3619:     if (!(untie(%hash))) {
                   3620:       return "error:$!";
                   3621:     }
                   3622:   } else {
                   3623:     return "error:$!";
                   3624:   }
                   3625:   return %returnhash;
1.167     albertel 3626: }
                   3627: 
1.9       www      3628: # ----------------------------------------------------------------------- Store
                   3629: 
                   3630: sub store {
1.124     www      3631:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3632:     my $home='';
                   3633: 
1.168     albertel 3634:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3635: 
1.213     www      3636:     $symb=&symbclean($symb);
1.122     albertel 3637:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3638: 
1.620     albertel 3639:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3640:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3641: 
                   3642:     &devalidate($symb,$stuname,$domain);
1.109     www      3643: 
                   3644:     $symb=escape($symb);
1.187     www      3645:     if (!$namespace) { 
1.620     albertel 3646:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3647:           return ''; 
                   3648:        } 
                   3649:     }
1.620     albertel 3650:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3651: 
                   3652:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3653:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3654: 
1.12      www      3655:     my $namevalue='';
1.800     albertel 3656:     foreach my $key (keys(%$storehash)) {
                   3657:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3658:     }
1.12      www      3659:     $namevalue=~s/\&$//;
1.187     www      3660:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3661:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3662: }
                   3663: 
1.47      www      3664: # -------------------------------------------------------------- Critical Store
                   3665: 
                   3666: sub cstore {
1.124     www      3667:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3668:     my $home='';
                   3669: 
1.168     albertel 3670:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3671: 
1.213     www      3672:     $symb=&symbclean($symb);
1.122     albertel 3673:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3674: 
1.620     albertel 3675:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3676:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3677: 
                   3678:     &devalidate($symb,$stuname,$domain);
1.109     www      3679: 
                   3680:     $symb=escape($symb);
1.187     www      3681:     if (!$namespace) { 
1.620     albertel 3682:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3683:           return ''; 
                   3684:        } 
                   3685:     }
1.620     albertel 3686:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3687: 
                   3688:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3689:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3690: 
1.47      www      3691:     my $namevalue='';
1.800     albertel 3692:     foreach my $key (keys(%$storehash)) {
                   3693:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3694:     }
1.47      www      3695:     $namevalue=~s/\&$//;
1.187     www      3696:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3697:     return critical
                   3698:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3699: }
                   3700: 
1.9       www      3701: # --------------------------------------------------------------------- Restore
                   3702: 
                   3703: sub restore {
1.124     www      3704:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3705:     my $home='';
                   3706: 
1.168     albertel 3707:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3708: 
1.122     albertel 3709:     if (!$symb) {
                   3710:       unless ($symb=escape(&symbread())) { return ''; }
                   3711:     } else {
1.213     www      3712:       $symb=&escape(&symbclean($symb));
1.122     albertel 3713:     }
1.188     www      3714:     if (!$namespace) { 
1.620     albertel 3715:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3716:           return ''; 
                   3717:        } 
                   3718:     }
1.620     albertel 3719:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3720:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3721:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3722:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3723: 
1.12      www      3724:     my %returnhash=();
1.800     albertel 3725:     foreach my $line (split(/\&/,$answer)) {
                   3726: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3727:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3728:     }
1.75      www      3729:     my $version;
                   3730:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3731:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3732:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3733:        }
1.75      www      3734:     }
1.13      www      3735:     return %returnhash;
1.34      www      3736: }
                   3737: 
                   3738: # ---------------------------------------------------------- Course Description
                   3739: 
                   3740: sub coursedescription {
1.731     albertel 3741:     my ($courseid,$args)=@_;
1.34      www      3742:     $courseid=~s/^\///;
1.49      www      3743:     $courseid=~s/\_/\//g;
1.34      www      3744:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3745:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3746:     my $normalid=$cdomain.'_'.$cnum;
                   3747:     # need to always cache even if we get errors otherwise we keep 
                   3748:     # trying and trying and trying to get the course description.
                   3749:     my %envhash=();
                   3750:     my %returnhash=();
1.731     albertel 3751:     
                   3752:     my $expiretime=600;
                   3753:     if ($env{'request.course.id'} eq $normalid) {
                   3754: 	$expiretime=120;
                   3755:     }
                   3756: 
                   3757:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3758:     if (!$args->{'freshen_cache'}
                   3759: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3760: 	foreach my $key (keys(%env)) {
                   3761: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3762: 	    my ($setting) = $1;
                   3763: 	    $returnhash{$setting} = $env{$key};
                   3764: 	}
                   3765: 	return %returnhash;
                   3766:     }
                   3767: 
                   3768:     # get the data agin
                   3769:     if (!$args->{'one_time'}) {
                   3770: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3771:     }
1.811     albertel 3772: 
1.34      www      3773:     if ($chome ne 'no_host') {
1.302     albertel 3774:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3775:        if (!exists($returnhash{'con_lost'})) {
                   3776:            $returnhash{'home'}= $chome;
                   3777: 	   $returnhash{'domain'} = $cdomain;
                   3778: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3779:            if (!defined($returnhash{'type'})) {
                   3780:                $returnhash{'type'} = 'Course';
                   3781:            }
1.130     albertel 3782:            while (my ($name,$value) = each %returnhash) {
1.53      www      3783:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3784:            }
1.270     www      3785:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3786:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3787: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3788:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3789:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3790:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3791:        }
                   3792:     }
1.731     albertel 3793:     if (!$args->{'one_time'}) {
1.949     raeburn  3794: 	&appenv(\%envhash);
1.731     albertel 3795:     }
1.302     albertel 3796:     return %returnhash;
1.461     www      3797: }
                   3798: 
                   3799: # -------------------------------------------------See if a user is privileged
                   3800: 
                   3801: sub privileged {
                   3802:     my ($username,$domain)=@_;
                   3803:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3804: 			&homeserver($username,$domain));
1.1033    raeburn  3805:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3806:         ($rolesdump =~ /^error:/)) {
                   3807:         return 0;
                   3808:     }
1.461     www      3809:     my $now=time;
                   3810:     if ($rolesdump ne '') {
1.800     albertel 3811:         foreach my $entry (split(/&/,$rolesdump)) {
                   3812: 	    if ($entry!~/^rolesdef_/) {
                   3813: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3814: 		$area=~s/\_\w\w$//;
                   3815: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3816: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3817: 		    my $active=1;
                   3818: 		    if ($tend) {
                   3819: 			if ($tend<$now) { $active=0; }
                   3820: 		    }
                   3821: 		    if ($tstart) {
                   3822: 			if ($tstart>$now) { $active=0; }
                   3823: 		    }
                   3824: 		    if ($active) { return 1; }
                   3825: 		}
                   3826: 	    }
                   3827: 	}
                   3828:     }
                   3829:     return 0;
1.9       www      3830: }
1.1       albertel 3831: 
1.103     harris41 3832: # -------------------------------------------------------- Get user privileges
1.11      www      3833: 
                   3834: sub rolesinit {
                   3835:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  3836:     my $now=time;
                   3837:     my %userroles = ('user.login.time' => $now);
1.11      www      3838:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033    raeburn  3839:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3840:         ($rolesdump =~ /^error:/)) { 
                   3841:         return \%userroles;
                   3842:     }
1.11      www      3843:     my %allroles=();
1.678     raeburn  3844:     my %allgroups=();   
                   3845:     my $group_privs;
1.11      www      3846: 
                   3847:     if ($rolesdump ne '') {
1.800     albertel 3848:         foreach my $entry (split(/&/,$rolesdump)) {
                   3849: 	  if ($entry!~/^rolesdef_/) {
                   3850:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3851: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3852:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3853: 	    if ($role=~/^cr/) { 
1.807     albertel 3854: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3855: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3856: 		    ($tend,$tstart)=split('_',$trest);
                   3857: 		} else {
                   3858: 		    $trole=$role;
                   3859: 		}
1.678     raeburn  3860:             } elsif ($role =~ m|^gr/|) {
                   3861:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3862:                 ($trole,$group_privs) = split(/\//,$trole);
                   3863:                 $group_privs = &unescape($group_privs);
1.587     albertel 3864: 	    } else {
                   3865: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3866: 	    }
1.743     albertel 3867: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3868: 					 $username);
                   3869: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3870:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3871:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3872:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3873: 		my $spec=$trole.'.'.$area;
                   3874: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3875: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3876:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3877:                 } elsif ($trole eq 'gr') {
                   3878:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3879: 		} else {
1.567     raeburn  3880:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3881: 		}
1.12      www      3882:             }
1.662     raeburn  3883:           }
1.191     harris41 3884:         }
1.743     albertel 3885:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3886:         $userroles{'user.adv'}    = $adv;
                   3887: 	$userroles{'user.author'} = $author;
1.620     albertel 3888:         $env{'user.adv'}=$adv;
1.11      www      3889:     }
1.743     albertel 3890:     return \%userroles;  
1.11      www      3891: }
                   3892: 
1.567     raeburn  3893: sub set_arearole {
                   3894:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3895: # log the associated role with the area
                   3896:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3897:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3898: }
                   3899: 
                   3900: sub custom_roleprivs {
                   3901:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3902:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3903:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3904:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3905:         my ($rdummy,$roledef)=
                   3906:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3907:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3908:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3909:             if (defined($syspriv)) {
                   3910:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3911:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3912:             }
                   3913:             if ($tdomain ne '') {
                   3914:                 if (defined($dompriv)) {
                   3915:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3916:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3917:                 }
                   3918:                 if (($trest ne '') && (defined($coursepriv))) {
                   3919:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3920:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3921:                 }
                   3922:             }
                   3923:         }
                   3924:     }
                   3925: }
                   3926: 
1.678     raeburn  3927: sub group_roleprivs {
                   3928:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3929:     my $access = 1;
                   3930:     my $now = time;
                   3931:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3932:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3933:     if ($access) {
1.811     albertel 3934:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3935:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3936:     }
                   3937: }
1.567     raeburn  3938: 
                   3939: sub standard_roleprivs {
                   3940:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3941:     if (defined($pr{$trole.':s'})) {
                   3942:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3943:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3944:     }
                   3945:     if ($tdomain ne '') {
                   3946:         if (defined($pr{$trole.':d'})) {
                   3947:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3948:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3949:         }
                   3950:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3951:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3952:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3953:         }
                   3954:     }
                   3955: }
                   3956: 
                   3957: sub set_userprivs {
1.678     raeburn  3958:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3959:     my $author=0;
                   3960:     my $adv=0;
1.678     raeburn  3961:     my %grouproles = ();
                   3962:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3963:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3964:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3965:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3966:                 $trole = $1;
                   3967:                 $area = $2;
1.681     raeburn  3968:                 $sec = $3;
                   3969:                 $extendedarea = $area.$sec;
                   3970:                 if (exists($$allgroups{$area})) {
                   3971:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3972:                         my $spec = $trole.'.'.$extendedarea;
                   3973:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3974:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3975:                     }
                   3976:                 }
                   3977:             }
                   3978:         }
                   3979:     }
1.800     albertel 3980:     foreach my $group (keys(%grouproles)) {
                   3981:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3982:     }
1.800     albertel 3983:     foreach my $role (keys(%{$allroles})) {
                   3984:         my %thesepriv;
1.941     raeburn  3985:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3986:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3987:             if ($item ne '') {
                   3988:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3989:                 if ($restrictions eq '') {
                   3990:                     $thesepriv{$privilege}='F';
                   3991:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3992:                     $thesepriv{$privilege}.=$restrictions;
                   3993:                 }
                   3994:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3995:             }
                   3996:         }
                   3997:         my $thesestr='';
1.800     albertel 3998:         foreach my $priv (keys(%thesepriv)) {
                   3999: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4000: 	}
                   4001:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4002:     }
                   4003:     return ($author,$adv);
                   4004: }
                   4005: 
1.994     raeburn  4006: sub role_status {
1.1002    raeburn  4007:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4008:     my @pwhere = ();
                   4009:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4010:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4011:         unless (!defined($$role) || $$role eq '') {
                   4012:             $$where=join('.',@pwhere);
                   4013:             $$trolecode=$$role.'.'.$$where;
                   4014:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4015:             $$tstatus='is';
                   4016:             if ($$tstart && $$tstart>$then) {
                   4017:                 $$tstatus='future';
1.1034    raeburn  4018:                 if ($$tstart<$now) {
                   4019:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4020:                         if (($$where ne '') && ($$role ne '')) {
                   4021:                             my (%allroles,%allgroups,$group_privs);
                   4022:                             my %userroles = (
                   4023:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4024:                             );
                   4025:                             my $spec=$$role.'.'.$$where;
                   4026:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4027:                             if ($$role eq 'gr') {
                   4028:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4029:                                                     $env{'user.name'})=@_;
                   4030:                                 my ($trole) = split('_',$role,1);
                   4031:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4032:                                 $group_privs = &unescape($group_privs);
                   4033:                             }
                   4034:                             if ($$role =~ /^cr\//) {
                   4035:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   4036:                             } elsif ($$role eq 'gr') {
                   4037:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4038:                                                     $env{'user.name'});
                   4039:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   4040:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4041:                                 $group_privs = &unescape($group_privs);
                   4042:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   4043:                             } else {
                   4044:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4045:                             }
                   4046:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4047:                             &appenv(\%userroles,[$$role,'cm']);
                   4048:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4049:                         }
                   4050:                     }
1.1034    raeburn  4051:                     $$tstatus = 'is';
1.1002    raeburn  4052:                 }
1.994     raeburn  4053:             }
                   4054:             if ($$tend) {
                   4055:                 if ($$tend<$then) {
                   4056:                     $$tstatus='expired';
                   4057:                 } elsif ($$tend<$now) {
                   4058:                     $$tstatus='will_not';
                   4059:                 }
                   4060:             }
                   4061:         }
                   4062:     }
                   4063: }
                   4064: 
                   4065: sub check_adhoc_privs {
1.1002    raeburn  4066:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4067:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4068:     if ($env{$cckey}) {
                   4069:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4070:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4071:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4072:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4073:         }
                   4074:     } else {
                   4075:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4076:     }
                   4077: }
                   4078: 
                   4079: sub set_adhoc_privileges {
                   4080: # role can be cc or ca
                   4081:     my ($dcdom,$pickedcourse,$role) = @_;
                   4082:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4083:     my $spec = $role.'.'.$area;
                   4084:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4085:                                   $env{'user.name'});
                   4086:     my %ccrole = ();
                   4087:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4088:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4089:     &appenv(\%userroles,[$role,'cm']);
                   4090:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4091:     &appenv( {'request.role'        => $spec,
                   4092:               'request.role.domain' => $dcdom,
                   4093:               'request.course.sec'  => ''
                   4094:              }
                   4095:            );
                   4096:     my $tadv=0;
                   4097:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4098:     &appenv({'request.role.adv'    => $tadv});
                   4099: }
                   4100: 
1.12      www      4101: # --------------------------------------------------------------- get interface
                   4102: 
                   4103: sub get {
1.131     albertel 4104:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4105:    my $items='';
1.800     albertel 4106:    foreach my $item (@$storearr) {
                   4107:        $items.=&escape($item).'&';
1.191     harris41 4108:    }
1.12      www      4109:    $items=~s/\&$//;
1.620     albertel 4110:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4111:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4112:    my $uhome=&homeserver($uname,$udomain);
                   4113: 
1.133     albertel 4114:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4115:    my @pairs=split(/\&/,$rep);
1.273     albertel 4116:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4117:      return @pairs;
                   4118:    }
1.15      www      4119:    my %returnhash=();
1.42      www      4120:    my $i=0;
1.800     albertel 4121:    foreach my $item (@$storearr) {
                   4122:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4123:       $i++;
1.191     harris41 4124:    }
1.15      www      4125:    return %returnhash;
1.27      www      4126: }
                   4127: 
                   4128: # --------------------------------------------------------------- del interface
                   4129: 
                   4130: sub del {
1.133     albertel 4131:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4132:    my $items='';
1.800     albertel 4133:    foreach my $item (@$storearr) {
                   4134:        $items.=&escape($item).'&';
1.191     harris41 4135:    }
1.984     neumanie 4136: 
1.27      www      4137:    $items=~s/\&$//;
1.620     albertel 4138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4139:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4140:    my $uhome=&homeserver($uname,$udomain);
                   4141:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4142: }
                   4143: 
                   4144: # -------------------------------------------------------------- dump interface
                   4145: 
                   4146: sub dump {
1.755     albertel 4147:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4148:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4149:     if (!$uname) { $uname=$env{'user.name'}; }
                   4150:     my $uhome=&homeserver($uname,$udomain);
                   4151:     if ($regexp) {
                   4152: 	$regexp=&escape($regexp);
                   4153:     } else {
                   4154: 	$regexp='.';
                   4155:     }
                   4156:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4157:     my @pairs=split(/\&/,$rep);
                   4158:     my %returnhash=();
                   4159:     foreach my $item (@pairs) {
                   4160: 	my ($key,$value)=split(/=/,$item,2);
                   4161: 	$key = &unescape($key);
                   4162: 	next if ($key =~ /^error: 2 /);
                   4163: 	$returnhash{$key}=&thaw_unescape($value);
                   4164:     }
                   4165:     return %returnhash;
1.407     www      4166: }
                   4167: 
1.717     albertel 4168: # --------------------------------------------------------- dumpstore interface
                   4169: 
                   4170: sub dumpstore {
                   4171:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4172:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4173:    if (!$uname) { $uname=$env{'user.name'}; }
                   4174:    my $uhome=&homeserver($uname,$udomain);
                   4175:    if ($regexp) {
                   4176:        $regexp=&escape($regexp);
                   4177:    } else {
                   4178:        $regexp='.';
                   4179:    }
                   4180:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4181:    my @pairs=split(/\&/,$rep);
                   4182:    my %returnhash=();
                   4183:    foreach my $item (@pairs) {
                   4184:        my ($key,$value)=split(/=/,$item,2);
                   4185:        next if ($key =~ /^error: 2 /);
                   4186:        $returnhash{$key}=&thaw_unescape($value);
                   4187:    }
                   4188:    return %returnhash;
1.717     albertel 4189: }
                   4190: 
1.407     www      4191: # -------------------------------------------------------------- keys interface
                   4192: 
                   4193: sub getkeys {
                   4194:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4195:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4196:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4197:    my $uhome=&homeserver($uname,$udomain);
                   4198:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4199:    my @keyarray=();
1.800     albertel 4200:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4201:       next if ($key =~ /^error: 2 /);
1.800     albertel 4202:       push(@keyarray,&unescape($key));
1.407     www      4203:    }
                   4204:    return @keyarray;
1.318     matthew  4205: }
                   4206: 
1.319     matthew  4207: # --------------------------------------------------------------- currentdump
                   4208: sub currentdump {
1.328     matthew  4209:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4210:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4211:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4212:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4213:    my $uhome = &homeserver($sname,$sdom);
                   4214:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4215:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4216:    #
1.318     matthew  4217:    my %returnhash=();
1.319     matthew  4218:    #
                   4219:    if ($rep eq "unknown_cmd") { 
                   4220:        # an old lond will not know currentdump
                   4221:        # Do a dump and make it look like a currentdump
1.822     albertel 4222:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4223:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4224:        my %hash = @tmp;
                   4225:        @tmp=();
1.424     matthew  4226:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4227:    } else {
                   4228:        my @pairs=split(/\&/,$rep);
1.800     albertel 4229:        foreach my $pair (@pairs) {
                   4230:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4231:            my ($symb,$param) = split(/:/,$key);
                   4232:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4233:                                                         &thaw_unescape($value);
1.319     matthew  4234:        }
1.191     harris41 4235:    }
1.12      www      4236:    return %returnhash;
1.424     matthew  4237: }
                   4238: 
                   4239: sub convert_dump_to_currentdump{
                   4240:     my %hash = %{shift()};
                   4241:     my %returnhash;
                   4242:     # Code ripped from lond, essentially.  The only difference
                   4243:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4244:     # we might run in to problems with parameter names =~ /^v\./
                   4245:     while (my ($key,$value) = each(%hash)) {
                   4246:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4247: 	$symb  = &unescape($symb);
                   4248: 	$param = &unescape($param);
1.424     matthew  4249:         next if ($v eq 'version' || $symb eq 'keys');
                   4250:         next if (exists($returnhash{$symb}) &&
                   4251:                  exists($returnhash{$symb}->{$param}) &&
                   4252:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4253:         $returnhash{$symb}->{$param}=$value;
                   4254:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4255:     }
                   4256:     #
                   4257:     # Remove all of the keys in the hashes which keep track of
                   4258:     # the version of the parameter.
                   4259:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4260:         # use a foreach because we are going to delete from the hash.
                   4261:         foreach my $key (keys(%$param_hash)) {
                   4262:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4263:         }
                   4264:     }
                   4265:     return \%returnhash;
1.12      www      4266: }
                   4267: 
1.627     albertel 4268: # ------------------------------------------------------ critical inc interface
                   4269: 
                   4270: sub cinc {
                   4271:     return &inc(@_,'critical');
                   4272: }
                   4273: 
1.449     matthew  4274: # --------------------------------------------------------------- inc interface
                   4275: 
                   4276: sub inc {
1.627     albertel 4277:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4278:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4279:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4280:     my $uhome=&homeserver($uname,$udomain);
                   4281:     my $items='';
                   4282:     if (! ref($store)) {
                   4283:         # got a single value, so use that instead
                   4284:         $items = &escape($store).'=&';
                   4285:     } elsif (ref($store) eq 'SCALAR') {
                   4286:         $items = &escape($$store).'=&';        
                   4287:     } elsif (ref($store) eq 'ARRAY') {
                   4288:         $items = join('=&',map {&escape($_);} @{$store});
                   4289:     } elsif (ref($store) eq 'HASH') {
                   4290:         while (my($key,$value) = each(%{$store})) {
                   4291:             $items.= &escape($key).'='.&escape($value).'&';
                   4292:         }
                   4293:     }
                   4294:     $items=~s/\&$//;
1.627     albertel 4295:     if ($critical) {
                   4296: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4297:     } else {
                   4298: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4299:     }
1.449     matthew  4300: }
                   4301: 
1.12      www      4302: # --------------------------------------------------------------- put interface
                   4303: 
                   4304: sub put {
1.134     albertel 4305:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4307:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4308:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4309:    my $items='';
1.800     albertel 4310:    foreach my $item (keys(%$storehash)) {
                   4311:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4312:    }
1.12      www      4313:    $items=~s/\&$//;
1.134     albertel 4314:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4315: }
                   4316: 
1.631     albertel 4317: # ------------------------------------------------------------ newput interface
                   4318: 
                   4319: sub newput {
                   4320:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4321:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4322:    if (!$uname) { $uname=$env{'user.name'}; }
                   4323:    my $uhome=&homeserver($uname,$udomain);
                   4324:    my $items='';
                   4325:    foreach my $key (keys(%$storehash)) {
                   4326:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4327:    }
                   4328:    $items=~s/\&$//;
                   4329:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4330: }
                   4331: 
                   4332: # ---------------------------------------------------------  putstore interface
                   4333: 
1.524     raeburn  4334: sub putstore {
1.715     albertel 4335:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4337:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4338:    my $uhome=&homeserver($uname,$udomain);
                   4339:    my $items='';
1.715     albertel 4340:    foreach my $key (keys(%$storehash)) {
                   4341:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4342:    }
1.715     albertel 4343:    $items=~s/\&$//;
1.716     albertel 4344:    my $esc_symb=&escape($symb);
                   4345:    my $esc_v=&escape($version);
1.715     albertel 4346:    my $reply =
1.716     albertel 4347:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4348: 	      $uhome);
                   4349:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4350:        # gfall back to way things use to be done
1.715     albertel 4351:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4352: 			    $uname);
1.524     raeburn  4353:    }
1.715     albertel 4354:    return $reply;
                   4355: }
                   4356: 
                   4357: sub old_putstore {
1.716     albertel 4358:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4359:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4360:     if (!$uname) { $uname=$env{'user.name'}; }
                   4361:     my $uhome=&homeserver($uname,$udomain);
                   4362:     my %newstorehash;
1.800     albertel 4363:     foreach my $item (keys(%$storehash)) {
                   4364: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4365: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4366:     }
                   4367:     my $items='';
                   4368:     my %allitems = ();
1.800     albertel 4369:     foreach my $item (keys(%newstorehash)) {
                   4370: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4371: 	    my $key = $1.':keys:'.$2;
                   4372: 	    $allitems{$key} .= $3.':';
                   4373: 	}
1.800     albertel 4374: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4375:     }
1.800     albertel 4376:     foreach my $item (keys(%allitems)) {
                   4377: 	$allitems{$item} =~ s/\:$//;
                   4378: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4379:     }
                   4380:     $items=~s/\&$//;
                   4381:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4382: }
                   4383: 
1.47      www      4384: # ------------------------------------------------------ critical put interface
                   4385: 
                   4386: sub cput {
1.134     albertel 4387:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4388:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4389:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4390:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4391:    my $items='';
1.800     albertel 4392:    foreach my $item (keys(%$storehash)) {
                   4393:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4394:    }
1.47      www      4395:    $items=~s/\&$//;
1.134     albertel 4396:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4397: }
                   4398: 
                   4399: # -------------------------------------------------------------- eget interface
                   4400: 
                   4401: sub eget {
1.133     albertel 4402:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4403:    my $items='';
1.800     albertel 4404:    foreach my $item (@$storearr) {
                   4405:        $items.=&escape($item).'&';
1.191     harris41 4406:    }
1.12      www      4407:    $items=~s/\&$//;
1.620     albertel 4408:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4409:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4410:    my $uhome=&homeserver($uname,$udomain);
                   4411:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4412:    my @pairs=split(/\&/,$rep);
                   4413:    my %returnhash=();
1.42      www      4414:    my $i=0;
1.800     albertel 4415:    foreach my $item (@$storearr) {
                   4416:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4417:       $i++;
1.191     harris41 4418:    }
1.12      www      4419:    return %returnhash;
                   4420: }
                   4421: 
1.667     albertel 4422: # ------------------------------------------------------------ tmpput interface
                   4423: sub tmpput {
1.802     raeburn  4424:     my ($storehash,$server,$context)=@_;
1.667     albertel 4425:     my $items='';
1.800     albertel 4426:     foreach my $item (keys(%$storehash)) {
                   4427: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4428:     }
                   4429:     $items=~s/\&$//;
1.802     raeburn  4430:     if (defined($context)) {
                   4431:         $items .= ':'.&escape($context);
                   4432:     }
1.667     albertel 4433:     return &reply("tmpput:$items",$server);
                   4434: }
                   4435: 
                   4436: # ------------------------------------------------------------ tmpget interface
                   4437: sub tmpget {
1.688     albertel 4438:     my ($token,$server)=@_;
                   4439:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4440:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4441:     my %returnhash;
                   4442:     foreach my $item (split(/\&/,$rep)) {
                   4443: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4444:         next if ($key =~ /^error: 2 /);
1.667     albertel 4445: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4446:     }
                   4447:     return %returnhash;
                   4448: }
                   4449: 
1.688     albertel 4450: # ------------------------------------------------------------ tmpget interface
                   4451: sub tmpdel {
                   4452:     my ($token,$server)=@_;
                   4453:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4454:     return &reply("tmpdel:$token",$server);
                   4455: }
                   4456: 
1.765     albertel 4457: # -------------------------------------------------- portfolio access checking
                   4458: 
                   4459: sub portfolio_access {
1.766     albertel 4460:     my ($requrl) = @_;
1.765     albertel 4461:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4462:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4463:     if ($result) {
                   4464:         my %setters;
                   4465:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4466:             my ($startblock,$endblock) =
                   4467:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4468:             if ($startblock && $endblock) {
                   4469:                 return 'B';
                   4470:             }
                   4471:         } else {
                   4472:             my ($startblock,$endblock) =
                   4473:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4474:             if ($startblock && $endblock) {
                   4475:                 return 'B';
                   4476:             }
                   4477:         }
                   4478:     }
1.765     albertel 4479:     if ($result eq 'ok') {
1.766     albertel 4480:        return 'F';
1.765     albertel 4481:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4482:        return 'A';
1.765     albertel 4483:     }
1.766     albertel 4484:     return '';
1.765     albertel 4485: }
                   4486: 
                   4487: sub get_portfolio_access {
1.767     albertel 4488:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4489: 
                   4490:     if (!ref($access_hash)) {
                   4491: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4492: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4493: 						   $file_name);
                   4494: 	$access_hash = $access_controls{$file_name};
                   4495:     }
                   4496: 
1.765     albertel 4497:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4498:     my $now = time;
                   4499:     if (ref($access_hash) eq 'HASH') {
                   4500:         foreach my $key (keys(%{$access_hash})) {
                   4501:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4502:             if ($start > $now) {
                   4503:                 next;
                   4504:             }
                   4505:             if ($end && $end<$now) {
                   4506:                 next;
                   4507:             }
                   4508:             if ($scope eq 'public') {
                   4509:                 $public = $key;
                   4510:                 last;
                   4511:             } elsif ($scope eq 'guest') {
                   4512:                 $guest = $key;
                   4513:             } elsif ($scope eq 'domains') {
                   4514:                 push(@domains,$key);
                   4515:             } elsif ($scope eq 'users') {
                   4516:                 push(@users,$key);
                   4517:             } elsif ($scope eq 'course') {
                   4518:                 push(@courses,$key);
                   4519:             } elsif ($scope eq 'group') {
                   4520:                 push(@groups,$key);
                   4521:             }
                   4522:         }
                   4523:         if ($public) {
                   4524:             return 'ok';
                   4525:         }
                   4526:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4527:             if ($guest) {
                   4528:                 return $guest;
                   4529:             }
                   4530:         } else {
                   4531:             if (@domains > 0) {
                   4532:                 foreach my $domkey (@domains) {
                   4533:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4534:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4535:                             return 'ok';
                   4536:                         }
                   4537:                     }
                   4538:                 }
                   4539:             }
                   4540:             if (@users > 0) {
                   4541:                 foreach my $userkey (@users) {
1.865     raeburn  4542:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4543:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4544:                             if (ref($item) eq 'HASH') {
                   4545:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4546:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4547:                                     return 'ok';
                   4548:                                 }
                   4549:                             }
                   4550:                         }
                   4551:                     } 
1.765     albertel 4552:                 }
                   4553:             }
                   4554:             my %roleshash;
                   4555:             my @courses_and_groups = @courses;
                   4556:             push(@courses_and_groups,@groups); 
                   4557:             if (@courses_and_groups > 0) {
                   4558:                 my (%allgroups,%allroles); 
                   4559:                 my ($start,$end,$role,$sec,$group);
                   4560:                 foreach my $envkey (%env) {
1.811     albertel 4561:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4562:                         my $cid = $2.'_'.$3; 
                   4563:                         if ($1 eq 'gr') {
                   4564:                             $group = $4;
                   4565:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4566:                         } else {
                   4567:                             if ($4 eq '') {
                   4568:                                 $sec = 'none';
                   4569:                             } else {
                   4570:                                 $sec = $4;
                   4571:                             }
                   4572:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4573:                         }
1.811     albertel 4574:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4575:                         my $cid = $2.'_'.$3;
                   4576:                         if ($4 eq '') {
                   4577:                             $sec = 'none';
                   4578:                         } else {
                   4579:                             $sec = $4;
                   4580:                         }
                   4581:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4582:                     }
                   4583:                 }
                   4584:                 if (keys(%allroles) == 0) {
                   4585:                     return;
                   4586:                 }
                   4587:                 foreach my $key (@courses_and_groups) {
                   4588:                     my %content = %{$$access_hash{$key}};
                   4589:                     my $cnum = $content{'number'};
                   4590:                     my $cdom = $content{'domain'};
                   4591:                     my $cid = $cdom.'_'.$cnum;
                   4592:                     if (!exists($allroles{$cid})) {
                   4593:                         next;
                   4594:                     }    
                   4595:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4596:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4597:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4598:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4599:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4600:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4601:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4602:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4603:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4604:                                         if (grep/^all$/,@sections) {
                   4605:                                             return 'ok';
                   4606:                                         } else {
                   4607:                                             if (grep/^$sec$/,@sections) {
                   4608:                                                 return 'ok';
                   4609:                                             }
                   4610:                                         }
                   4611:                                     }
                   4612:                                 }
                   4613:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4614:                                     if (grep/^none$/,@groups) {
                   4615:                                         return 'ok';
                   4616:                                     }
                   4617:                                 } else {
                   4618:                                     if (grep/^all$/,@groups) {
                   4619:                                         return 'ok';
                   4620:                                     } 
                   4621:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4622:                                         if (grep/^$group$/,@groups) {
                   4623:                                             return 'ok';
                   4624:                                         }
                   4625:                                     }
                   4626:                                 } 
                   4627:                             }
                   4628:                         }
                   4629:                     }
                   4630:                 }
                   4631:             }
                   4632:             if ($guest) {
                   4633:                 return $guest;
                   4634:             }
                   4635:         }
                   4636:     }
                   4637:     return;
                   4638: }
                   4639: 
                   4640: sub course_group_datechecker {
                   4641:     my ($dates,$now,$status) = @_;
                   4642:     my ($start,$end) = split(/\./,$dates);
                   4643:     if (!$start && !$end) {
                   4644:         return 'ok';
                   4645:     }
                   4646:     if (grep/^active$/,@{$status}) {
                   4647:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4648:             return 'ok';
                   4649:         }
                   4650:     }
                   4651:     if (grep/^previous$/,@{$status}) {
                   4652:         if ($end > $now ) {
                   4653:             return 'ok';
                   4654:         }
                   4655:     }
                   4656:     if (grep/^future$/,@{$status}) {
                   4657:         if ($start > $now) {
                   4658:             return 'ok';
                   4659:         }
                   4660:     }
                   4661:     return; 
                   4662: }
                   4663: 
                   4664: sub parse_portfolio_url {
                   4665:     my ($url) = @_;
                   4666: 
                   4667:     my ($type,$udom,$unum,$group,$file_name);
                   4668:     
1.823     albertel 4669:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4670: 	$type = 1;
                   4671:         $udom = $1;
                   4672:         $unum = $2;
                   4673:         $file_name = $3;
1.823     albertel 4674:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4675: 	$type = 2;
                   4676:         $udom = $1;
                   4677:         $unum = $2;
                   4678:         $group = $3;
                   4679:         $file_name = $3.'/'.$4;
                   4680:     }
                   4681:     if (wantarray) {
                   4682: 	return ($type,$udom,$unum,$file_name,$group);
                   4683:     }
                   4684:     return $type;
                   4685: }
                   4686: 
                   4687: sub is_portfolio_url {
                   4688:     my ($url) = @_;
                   4689:     return scalar(&parse_portfolio_url($url));
                   4690: }
                   4691: 
1.798     raeburn  4692: sub is_portfolio_file {
                   4693:     my ($file) = @_;
1.820     raeburn  4694:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4695:         return 1;
                   4696:     }
                   4697:     return;
                   4698: }
                   4699: 
1.976     raeburn  4700: sub usertools_access {
1.985     raeburn  4701:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4702:     my ($access,%tools);
                   4703:     if ($context eq '') {
                   4704:         $context = 'tools';
                   4705:     }
                   4706:     if ($context eq 'requestcourses') {
                   4707:         %tools = (
                   4708:                       official   => 1,
                   4709:                       unofficial => 1,
1.1006    raeburn  4710:                       community  => 1,
1.985     raeburn  4711:                  );
                   4712:     } else {
                   4713:         %tools = (
                   4714:                       aboutme   => 1,
                   4715:                       blog      => 1,
                   4716:                       portfolio => 1,
                   4717:                  );
                   4718:     }
1.976     raeburn  4719:     return if (!defined($tools{$tool}));
                   4720: 
                   4721:     if ((!defined($udom)) || (!defined($uname))) {
                   4722:         $udom = $env{'user.domain'};
                   4723:         $uname = $env{'user.name'};
                   4724:     }
                   4725: 
1.978     raeburn  4726:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4727:         if ($action ne 'reload') {
1.985     raeburn  4728:             if ($context eq 'requestcourses') {
                   4729:                 return $env{'environment.canrequest.'.$tool};
                   4730:             } else {
                   4731:                 return $env{'environment.availabletools.'.$tool};
                   4732:             }
                   4733:         }
1.976     raeburn  4734:     }
                   4735: 
                   4736:     my ($toolstatus,$inststatus);
                   4737: 
1.985     raeburn  4738:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4739:          ($action ne 'reload')) {
                   4740:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4741:         $inststatus = $env{'environment.inststatus'};
                   4742:     } else {
1.1025    raeburn  4743:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4744:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4745:         $inststatus = $userenv{'inststatus'};
                   4746:     }
                   4747: 
                   4748:     if ($toolstatus ne '') {
                   4749:         if ($toolstatus) {
                   4750:             $access = 1;
                   4751:         } else {
                   4752:             $access = 0;
                   4753:         }
                   4754:         return $access;
                   4755:     }
                   4756: 
                   4757:     my $is_adv = &is_advanced_user($udom,$uname);
                   4758:     my %domdef = &get_domain_defaults($udom);
                   4759:     if (ref($domdef{$tool}) eq 'HASH') {
                   4760:         if ($is_adv) {
                   4761:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4762:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4763:                     $access = 1;
                   4764:                 } else {
                   4765:                     $access = 0;
                   4766:                 }
                   4767:                 return $access;
                   4768:             }
                   4769:         }
                   4770:         if ($inststatus ne '') {
                   4771:             my ($hasaccess,$hasnoaccess);
                   4772:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4773:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4774:                     if ($domdef{$tool}{$affiliation}) {
                   4775:                         $hasaccess = 1;
                   4776:                     } else {
                   4777:                         $hasnoaccess = 1;
                   4778:                     }
                   4779:                 }
                   4780:             }
                   4781:             if ($hasaccess || $hasnoaccess) {
                   4782:                 if ($hasaccess) {
                   4783:                     $access = 1;
                   4784:                 } elsif ($hasnoaccess) {
                   4785:                     $access = 0; 
                   4786:                 }
                   4787:                 return $access;
                   4788:             }
                   4789:         } else {
                   4790:             if ($domdef{$tool}{'default'} ne '') {
                   4791:                 if ($domdef{$tool}{'default'}) {
                   4792:                     $access = 1;
                   4793:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4794:                     $access = 0;
                   4795:                 }
                   4796:                 return $access;
                   4797:             }
                   4798:         }
                   4799:     } else {
1.985     raeburn  4800:         if ($context eq 'tools') {
                   4801:             $access = 1;
                   4802:         } else {
                   4803:             $access = 0;
                   4804:         }
1.976     raeburn  4805:         return $access;
                   4806:     }
                   4807: }
                   4808: 
                   4809: sub is_advanced_user {
                   4810:     my ($udom,$uname) = @_;
                   4811:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4812:     my %allroles;
                   4813:     my $is_adv;
                   4814:     foreach my $role (keys(%roleshash)) {
                   4815:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4816:         my $area = '/'.$tdomain.'/'.$trest;
                   4817:         if ($sec ne '') {
                   4818:             $area .= '/'.$sec;
                   4819:         }
                   4820:         if (($area ne '') && ($trole ne '')) {
                   4821:             my $spec=$trole.'.'.$area;
                   4822:             if ($trole =~ /^cr\//) {
                   4823:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4824:             } elsif ($trole ne 'gr') {
                   4825:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4826:             }
                   4827:         }
                   4828:     }
                   4829:     foreach my $role (keys(%allroles)) {
                   4830:         last if ($is_adv);
                   4831:         foreach my $item (split(/:/,$allroles{$role})) {
                   4832:             if ($item ne '') {
                   4833:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4834:                 if ($privilege eq 'adv') {
                   4835:                     $is_adv = 1;
                   4836:                     last;
                   4837:                 }
                   4838:             }
                   4839:         }
                   4840:     }
                   4841:     return $is_adv;
                   4842: }
1.798     raeburn  4843: 
1.1035    raeburn  4844: sub check_can_request {
1.1036    raeburn  4845:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  4846:     my $canreq = 0;
                   4847:     my ($types,$typename) = &Apache::loncommon::course_types();
                   4848:     my @options = ('approval','validate','autolimit');
                   4849:     my $optregex = join('|',@options);
                   4850:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   4851:         foreach my $type (@{$types}) {
                   4852:             if (&usertools_access($env{'user.name'},
                   4853:                                   $env{'user.domain'},
                   4854:                                   $type,undef,'requestcourses')) {
                   4855:                 $canreq ++;
1.1036    raeburn  4856:                 if (ref($request_domains) eq 'HASH') {
                   4857:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   4858:                 }
1.1035    raeburn  4859:                 if ($dom eq $env{'user.domain'}) {
                   4860:                     $can_request->{$type} = 1;
                   4861:                 }
                   4862:             }
                   4863:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   4864:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   4865:                 if (@curr > 0) {
1.1036    raeburn  4866:                     foreach my $item (@curr) {
                   4867:                         if (ref($request_domains) eq 'HASH') {
                   4868:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   4869:                             if ($otherdom ne '') {
                   4870:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   4871:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   4872:                                         push(@{$request_domains->{$type}},$otherdom);
                   4873:                                     }
                   4874:                                 } else {
                   4875:                                     push(@{$request_domains->{$type}},$otherdom);
                   4876:                                 }
                   4877:                             }
                   4878:                         }
                   4879:                     }
                   4880:                     unless($dom eq $env{'user.domain'}) {
                   4881:                         $canreq ++;
1.1035    raeburn  4882:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   4883:                             $can_request->{$type} = 1;
                   4884:                         }
                   4885:                     }
                   4886:                 }
                   4887:             }
                   4888:         }
                   4889:     }
                   4890:     return $canreq;
                   4891: }
                   4892: 
1.341     www      4893: # ---------------------------------------------- Custom access rule evaluation
                   4894: 
                   4895: sub customaccess {
                   4896:     my ($priv,$uri)=@_;
1.807     albertel 4897:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4898:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4899:     $udom = &LONCAPA::clean_domain($udom);
                   4900:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4901:     my $access=0;
1.800     albertel 4902:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4903: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4904: 	if ($type eq 'user') {
                   4905: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4906: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4907: 		if ($tdom) {
                   4908: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4909: 		}
1.896     albertel 4910: 		if ($tuname) {
                   4911: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4912: 		}
                   4913: 		$access=($effect eq 'allow');
                   4914: 		last;
                   4915: 	    }
                   4916: 	} else {
                   4917: 	    if ($role) {
                   4918: 		if ($role ne $urole) { next; }
                   4919: 	    }
                   4920: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4921: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4922: 		if ($tdom) {
                   4923: 		    if ($tdom ne $udom) { next; }
                   4924: 		}
                   4925: 		if ($tcrs) {
                   4926: 		    if ($tcrs ne $ucrs) { next; }
                   4927: 		}
                   4928: 		if ($tsec) {
                   4929: 		    if ($tsec ne $usec) { next; }
                   4930: 		}
                   4931: 		$access=($effect eq 'allow');
                   4932: 		last;
                   4933: 	    }
                   4934: 	    if ($realm eq '' && $role eq '') {
                   4935: 		$access=($effect eq 'allow');
                   4936: 	    }
1.402     bowersj2 4937: 	}
1.341     www      4938:     }
                   4939:     return $access;
                   4940: }
                   4941: 
1.103     harris41 4942: # ------------------------------------------------- Check for a user privilege
1.12      www      4943: 
                   4944: sub allowed {
1.810     raeburn  4945:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4946:     my $ver_orguri=$uri;
1.439     www      4947:     $uri=&deversion($uri);
1.152     www      4948:     my $orguri=$uri;
1.52      www      4949:     $uri=&declutter($uri);
1.809     raeburn  4950: 
1.810     raeburn  4951:     if ($priv eq 'evb') {
                   4952: # Evade communication block restrictions for specified role in a course
                   4953:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4954:             return $1;
                   4955:         } else {
                   4956:             return;
                   4957:         }
                   4958:     }
                   4959: 
1.620     albertel 4960:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4961: # Free bre access to adm and meta resources
1.775     albertel 4962:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4963: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4964: 	&& ($priv eq 'bre')) {
1.14      www      4965: 	return 'F';
1.159     www      4966:     }
                   4967: 
1.545     banghart 4968: # Free bre access to user's own portfolio contents
1.714     raeburn  4969:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4970:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4971: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4972:         my %setters;
                   4973:         my ($startblock,$endblock) = 
                   4974:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4975:         if ($startblock && $endblock) {
                   4976:             return 'B';
                   4977:         } else {
                   4978:             return 'F';
                   4979:         }
1.545     banghart 4980:     }
                   4981: 
1.762     raeburn  4982: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4983:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4984:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4985:         if (exists($env{'request.course.id'})) {
                   4986:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4987:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4988:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4989:                 my $courseprivid=$env{'request.course.id'};
                   4990:                 $courseprivid=~s/\_/\//;
                   4991:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4992:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4993:                     return $1; 
1.762     raeburn  4994:                 } else {
                   4995:                     if ($env{'request.course.sec'}) {
                   4996:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4997:                     }
                   4998:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4999:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5000:                         return $2;
                   5001:                     }
1.714     raeburn  5002:                 }
                   5003:             }
                   5004:         }
                   5005:     }
                   5006: 
1.159     www      5007: # Free bre to public access
                   5008: 
                   5009:     if ($priv eq 'bre') {
1.238     www      5010:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5011: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5012:            return 'F'; 
                   5013:         }
1.238     www      5014:         if ($copyright eq 'priv') {
                   5015:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5016: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5017: 		return '';
                   5018:             }
                   5019:         }
                   5020:         if ($copyright eq 'domain') {
                   5021:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5022: 	    unless (($env{'user.domain'} eq $1) ||
                   5023:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5024: 		return '';
                   5025:             }
1.262     matthew  5026:         }
1.620     albertel 5027:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5028:             # Library role, so allow browsing of resources in this domain.
                   5029:             return 'F';
1.238     www      5030:         }
1.341     www      5031:         if ($copyright eq 'custom') {
                   5032: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5033:         }
1.14      www      5034:     }
1.264     matthew  5035:     # Domain coordinator is trying to create a course
1.620     albertel 5036:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5037:         # uri is the requested domain in this case.
                   5038:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5039:         # a role of dc for the domain in question.
1.620     albertel 5040:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5041:     }
1.29      www      5042: 
1.52      www      5043:     my $thisallowed='';
                   5044:     my $statecond=0;
                   5045:     my $courseprivid='';
                   5046: 
                   5047: # Course
                   5048: 
1.620     albertel 5049:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5050:        $thisallowed.=$1;
                   5051:     }
1.29      www      5052: 
1.52      www      5053: # Domain
                   5054: 
1.620     albertel 5055:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5056:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      5057:        $thisallowed.=$1;
                   5058:     }
1.52      www      5059: 
                   5060: # Course: uri itself is a course
1.66      www      5061:     my $courseuri=$uri;
                   5062:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5063:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5064: 
1.620     albertel 5065:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5066:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      5067:        $thisallowed.=$1;
                   5068:     }
1.29      www      5069: 
1.665     albertel 5070: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5071: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5072:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5073: 	$thisallowed='';
1.671     raeburn  5074:         my ($match)=&is_on_map($uri);
                   5075:         if ($match) {
                   5076:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5077:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5078:                 $thisallowed.=$1;
                   5079:             }
                   5080:         } else {
1.705     albertel 5081:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5082:             if ($refuri) {
                   5083:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5084:                     $thisallowed='F';
1.671     raeburn  5085:                 } else {
                   5086:                     $refuri=&declutter($refuri);
                   5087:                     my ($match) = &is_on_map($refuri);
                   5088:                     if ($match) {
                   5089:                         $thisallowed='F';
                   5090:                     }
1.669     raeburn  5091:                 }
1.671     raeburn  5092:             }
                   5093:         }
1.314     www      5094:     }
1.492     albertel 5095: 
1.766     albertel 5096:     if ($priv eq 'bre'
                   5097: 	&& $thisallowed ne 'F' 
                   5098: 	&& $thisallowed ne '2'
                   5099: 	&& &is_portfolio_url($uri)) {
                   5100: 	$thisallowed = &portfolio_access($uri);
                   5101:     }
                   5102:     
1.52      www      5103: # Full access at system, domain or course-wide level? Exit.
1.29      www      5104:     if ($thisallowed=~/F/) {
                   5105: 	return 'F';
                   5106:     }
                   5107: 
1.52      www      5108: # If this is generating or modifying users, exit with special codes
1.29      www      5109: 
1.643     www      5110:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5111: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5112: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5113: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5114: 	    unless ($auname) { return $thisallowed; }
                   5115: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5116: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5117: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5118: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5119: 	}
1.52      www      5120: 	return $thisallowed;
                   5121:     }
                   5122: #
1.103     harris41 5123: # Gathered so far: system, domain and course wide privileges
1.52      www      5124: #
                   5125: # Course: See if uri or referer is an individual resource that is part of 
                   5126: # the course
                   5127: 
1.620     albertel 5128:     if ($env{'request.course.id'}) {
1.232     www      5129: 
1.620     albertel 5130:        $courseprivid=$env{'request.course.id'};
                   5131:        if ($env{'request.course.sec'}) {
                   5132:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5133:        }
                   5134:        $courseprivid=~s/\_/\//;
                   5135:        my $checkreferer=1;
1.232     www      5136:        my ($match,$cond)=&is_on_map($uri);
                   5137:        if ($match) {
                   5138:            $statecond=$cond;
1.620     albertel 5139:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5140:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5141:                $thisallowed.=$1;
                   5142:                $checkreferer=0;
                   5143:            }
1.29      www      5144:        }
1.83      www      5145:        
1.148     www      5146:        if ($checkreferer) {
1.620     albertel 5147: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5148:             unless ($refuri) {
1.800     albertel 5149:                 foreach my $key (keys(%env)) {
                   5150: 		    if ($key=~/^httpref\..*\*/) {
                   5151: 			my $pattern=$key;
1.156     www      5152:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5153:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5154:                         $pattern=~s/\//\\\//g;
1.152     www      5155:                         if ($orguri=~/$pattern/) {
1.800     albertel 5156: 			    $refuri=$env{$key};
1.148     www      5157:                         }
                   5158:                     }
1.191     harris41 5159:                 }
1.148     www      5160:             }
1.232     www      5161: 
1.148     www      5162:          if ($refuri) { 
1.152     www      5163: 	  $refuri=&declutter($refuri);
1.232     www      5164:           my ($match,$cond)=&is_on_map($refuri);
                   5165:             if ($match) {
                   5166:               my $refstatecond=$cond;
1.620     albertel 5167:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5168:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5169:                   $thisallowed.=$1;
1.53      www      5170:                   $uri=$refuri;
                   5171:                   $statecond=$refstatecond;
1.52      www      5172:               }
                   5173:           }
1.148     www      5174:         }
1.29      www      5175:        }
1.52      www      5176:    }
1.29      www      5177: 
1.52      www      5178: #
1.103     harris41 5179: # Gathered now: all privileges that could apply, and condition number
1.52      www      5180: # 
                   5181: #
                   5182: # Full or no access?
                   5183: #
1.29      www      5184: 
1.52      www      5185:     if ($thisallowed=~/F/) {
                   5186: 	return 'F';
                   5187:     }
1.29      www      5188: 
1.52      www      5189:     unless ($thisallowed) {
                   5190:         return '';
                   5191:     }
1.29      www      5192: 
1.52      www      5193: # Restrictions exist, deal with them
                   5194: #
                   5195: #   C:according to course preferences
                   5196: #   R:according to resource settings
                   5197: #   L:unless locked
                   5198: #   X:according to user session state
                   5199: #
                   5200: 
                   5201: # Possibly locked functionality, check all courses
1.54      www      5202: # Locks might take effect only after 10 minutes cache expiration for other
                   5203: # courses, and 2 minutes for current course
1.52      www      5204: 
                   5205:     my $envkey;
                   5206:     if ($thisallowed=~/L/) {
1.1000    raeburn  5207:         foreach $envkey (keys(%env)) {
1.54      www      5208:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5209:                my $courseid=$2;
                   5210:                my $roleid=$1.'.'.$2;
1.92      www      5211:                $courseid=~s/^\///;
1.54      www      5212:                my $expiretime=600;
1.620     albertel 5213:                if ($env{'request.role'} eq $roleid) {
1.54      www      5214: 		  $expiretime=120;
                   5215:                }
                   5216: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5217:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5218:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5219: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5220:                }
1.620     albertel 5221:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5222:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5223: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5224:                        &log($env{'user.domain'},$env{'user.name'},
                   5225:                             $env{'user.home'},
1.57      www      5226:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5227:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5228:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5229: 		       return '';
                   5230:                    }
                   5231:                }
1.620     albertel 5232:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5233:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5234: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5235:                        &log($env{'user.domain'},$env{'user.name'},
                   5236:                             $env{'user.home'},
1.57      www      5237:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5238:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5239:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5240: 		       return '';
                   5241:                    }
                   5242:                }
                   5243: 	   }
1.29      www      5244:        }
1.52      www      5245:     }
                   5246:    
                   5247: #
                   5248: # Rest of the restrictions depend on selected course
                   5249: #
                   5250: 
1.620     albertel 5251:     unless ($env{'request.course.id'}) {
1.766     albertel 5252: 	if ($thisallowed eq 'A') {
                   5253: 	    return 'A';
1.814     raeburn  5254:         } elsif ($thisallowed eq 'B') {
                   5255:             return 'B';
1.766     albertel 5256: 	} else {
                   5257: 	    return '1';
                   5258: 	}
1.52      www      5259:     }
1.29      www      5260: 
1.52      www      5261: #
                   5262: # Now user is definitely in a course
                   5263: #
1.53      www      5264: 
                   5265: 
                   5266: # Course preferences
                   5267: 
                   5268:    if ($thisallowed=~/C/) {
1.620     albertel 5269:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5270:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5271:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5272: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5273: 	   if ($priv ne 'pch') { 
                   5274: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5275: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5276: 			$env{'request.course.id'});
                   5277: 	   }
1.237     www      5278:            return '';
                   5279:        }
                   5280: 
1.620     albertel 5281:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5282: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5283: 	   if ($priv ne 'pch') { 
                   5284: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5285: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5286: 			$env{'request.course.id'});
                   5287: 	   }
1.54      www      5288:            return '';
                   5289:        }
1.53      www      5290:    }
                   5291: 
                   5292: # Resource preferences
                   5293: 
                   5294:    if ($thisallowed=~/R/) {
1.620     albertel 5295:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5296:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5297: 	   if ($priv ne 'pch') { 
                   5298: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5299: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5300: 	   }
                   5301: 	   return '';
1.54      www      5302:        }
1.53      www      5303:    }
1.30      www      5304: 
1.246     www      5305: # Restricted by state or randomout?
1.30      www      5306: 
1.52      www      5307:    if ($thisallowed=~/X/) {
1.620     albertel 5308:       if ($env{'acc.randomout'}) {
1.579     albertel 5309: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5310:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5311:             return ''; 
                   5312:          }
1.247     www      5313:       }
                   5314:       if (&condval($statecond)) {
1.52      www      5315: 	 return '2';
                   5316:       } else {
                   5317:          return '';
                   5318:       }
                   5319:    }
1.30      www      5320: 
1.766     albertel 5321:     if ($thisallowed eq 'A') {
                   5322: 	return 'A';
1.814     raeburn  5323:     } elsif ($thisallowed eq 'B') {
                   5324:         return 'B';
1.766     albertel 5325:     }
1.52      www      5326:    return 'F';
1.232     www      5327: }
                   5328: 
1.710     albertel 5329: sub split_uri_for_cond {
                   5330:     my $uri=&deversion(&declutter(shift));
                   5331:     my @uriparts=split(/\//,$uri);
                   5332:     my $filename=pop(@uriparts);
                   5333:     my $pathname=join('/',@uriparts);
                   5334:     return ($pathname,$filename);
                   5335: }
1.232     www      5336: # --------------------------------------------------- Is a resource on the map?
                   5337: 
                   5338: sub is_on_map {
1.710     albertel 5339:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5340:     #Trying to find the conditional for the file
1.620     albertel 5341:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5342: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5343:     if ($match) {
1.289     bowersj2 5344: 	return (1,$1);
                   5345:     } else {
1.434     www      5346: 	return (0,0);
1.289     bowersj2 5347:     }
1.12      www      5348: }
                   5349: 
1.427     www      5350: # --------------------------------------------------------- Get symb from alias
                   5351: 
                   5352: sub get_symb_from_alias {
                   5353:     my $symb=shift;
                   5354:     my ($map,$resid,$url)=&decode_symb($symb);
                   5355: # Already is a symb
                   5356:     if ($url) { return $symb; }
                   5357: # Must be an alias
                   5358:     my $aliassymb='';
                   5359:     my %bighash;
1.620     albertel 5360:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5361:                             &GDBM_READER(),0640)) {
                   5362:         my $rid=$bighash{'mapalias_'.$symb};
                   5363: 	if ($rid) {
                   5364: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5365: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5366: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5367: 	}
                   5368:         untie %bighash;
                   5369:     }
                   5370:     return $aliassymb;
                   5371: }
                   5372: 
1.12      www      5373: # ----------------------------------------------------------------- Define Role
                   5374: 
                   5375: sub definerole {
                   5376:   if (allowed('mcr','/')) {
                   5377:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5378:     foreach my $role (split(':',$sysrole)) {
                   5379: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5380:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5381:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5382: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5383:                return "refused:s:$crole&$cqual"; 
                   5384:             }
                   5385:         }
1.191     harris41 5386:     }
1.800     albertel 5387:     foreach my $role (split(':',$domrole)) {
                   5388: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5389:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5390:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5391: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5392:                return "refused:d:$crole&$cqual"; 
                   5393:             }
                   5394:         }
1.191     harris41 5395:     }
1.800     albertel 5396:     foreach my $role (split(':',$courole)) {
                   5397: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5398:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5399:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5400: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5401:                return "refused:c:$crole&$cqual"; 
                   5402:             }
                   5403:         }
1.191     harris41 5404:     }
1.620     albertel 5405:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5406:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5407: 	        "rolesdef_$rolename=".
                   5408:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5409:     return reply($command,$env{'user.home'});
1.12      www      5410:   } else {
                   5411:     return 'refused';
                   5412:   }
1.105     harris41 5413: }
                   5414: 
                   5415: # ---------------- Make a metadata query against the network of library servers
                   5416: 
                   5417: sub metadata_query {
1.244     matthew  5418:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5419:     my %rhash;
1.845     albertel 5420:     my %libserv = &all_library();
1.244     matthew  5421:     my @server_list = (defined($server_array) ? @$server_array
                   5422:                                               : keys(%libserv) );
                   5423:     for my $server (@server_list) {
1.118     harris41 5424: 	unless ($custom or $customshow) {
                   5425: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5426: 	    $rhash{$server}=$reply;
                   5427: 	}
                   5428: 	else {
                   5429: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5430: 			     &escape($custom).':'.&escape($customshow),
                   5431: 			     $server);
                   5432: 	    $rhash{$server}=$reply;
                   5433: 	}
1.112     harris41 5434:     }
1.118     harris41 5435:     return \%rhash;
1.240     www      5436: }
                   5437: 
                   5438: # ----------------------------------------- Send log queries and wait for reply
                   5439: 
                   5440: sub log_query {
                   5441:     my ($uname,$udom,$query,%filters)=@_;
                   5442:     my $uhome=&homeserver($uname,$udom);
                   5443:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5444:     my $uhost=&hostname($uhome);
1.800     albertel 5445:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5446:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5447:                        $uhome);
1.479     albertel 5448:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5449:     return get_query_reply($queryid);
                   5450: }
                   5451: 
1.818     raeburn  5452: # -------------------------- Update MySQL table for portfolio file
                   5453: 
                   5454: sub update_portfolio_table {
1.821     raeburn  5455:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5456:     if ($group ne '') {
                   5457:         $file_name =~s /^\Q$group\E//;
                   5458:     }
1.818     raeburn  5459:     my $homeserver = &homeserver($uname,$udom);
                   5460:     my $queryid=
1.821     raeburn  5461:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5462:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5463:     my $reply = &get_query_reply($queryid);
                   5464:     return $reply;
                   5465: }
                   5466: 
1.899     raeburn  5467: # -------------------------- Update MySQL allusers table
                   5468: 
                   5469: sub update_allusers_table {
                   5470:     my ($uname,$udom,$names) = @_;
                   5471:     my $homeserver = &homeserver($uname,$udom);
                   5472:     my $queryid=
                   5473:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5474:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5475:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5476:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5477:                'generation='.&escape($names->{'generation'}).'%%'.
                   5478:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5479:                'id='.&escape($names->{'id'}),$homeserver);
                   5480:     my $reply = &get_query_reply($queryid);
                   5481:     return $reply;
                   5482: }
                   5483: 
1.508     raeburn  5484: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5485: 
                   5486: sub fetch_enrollment_query {
1.511     raeburn  5487:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5488:     my $homeserver;
1.547     raeburn  5489:     my $maxtries = 1;
1.508     raeburn  5490:     if ($context eq 'automated') {
                   5491:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5492:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5493:     } else {
                   5494:         $homeserver = &homeserver($cnum,$dom);
                   5495:     }
1.838     albertel 5496:     my $host=&hostname($homeserver);
1.506     raeburn  5497:     my $cmd = '';
1.1000    raeburn  5498:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5499:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5500:     }
                   5501:     $cmd =~ s/%%$//;
                   5502:     $cmd = &escape($cmd);
                   5503:     my $query = 'fetchenrollment';
1.620     albertel 5504:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5505:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5506:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5507:         return 'error: '.$queryid;
                   5508:     }
1.506     raeburn  5509:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5510:     my $tries = 1;
                   5511:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5512:         $reply = &get_query_reply($queryid);
                   5513:         $tries ++;
                   5514:     }
1.526     raeburn  5515:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5516:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5517:     } else {
1.901     albertel 5518:         my @responses = split(/:/,$reply);
1.515     raeburn  5519:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5520:             foreach my $line (@responses) {
                   5521:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5522:                 $$replyref{$key} = $value;
                   5523:             }
                   5524:         } else {
1.506     raeburn  5525:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5526:             foreach my $line (@responses) {
                   5527:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5528:                 $$replyref{$key} = $value;
                   5529:                 if ($value > 0) {
1.800     albertel 5530:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5531:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5532:                         my $destname = $pathname.'/'.$filename;
                   5533:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5534:                         if ($xml_classlist =~ /^error/) {
                   5535:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5536:                         } else {
1.506     raeburn  5537:                             if ( open(FILE,">$destname") ) {
                   5538:                                 print FILE &unescape($xml_classlist);
                   5539:                                 close(FILE);
1.526     raeburn  5540:                             } else {
                   5541:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5542:                             }
                   5543:                         }
                   5544:                     }
                   5545:                 }
                   5546:             }
                   5547:         }
                   5548:         return 'ok';
                   5549:     }
                   5550:     return 'error';
                   5551: }
                   5552: 
1.242     www      5553: sub get_query_reply {
                   5554:     my $queryid=shift;
1.240     www      5555:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5556:     my $reply='';
                   5557:     for (1..100) {
                   5558: 	sleep 2;
                   5559:         if (-e $replyfile.'.end') {
1.448     albertel 5560: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5561: 		$reply = join('',<$fh>);
                   5562: 		close($fh);
1.240     www      5563: 	   } else { return 'error: reply_file_error'; }
1.242     www      5564:            return &unescape($reply);
                   5565: 	}
1.240     www      5566:     }
1.242     www      5567:     return 'timeout:'.$queryid;
1.240     www      5568: }
                   5569: 
                   5570: sub courselog_query {
1.241     www      5571: #
                   5572: # possible filters:
                   5573: # url: url or symb
                   5574: # username
                   5575: # domain
                   5576: # action: view, submit, grade
                   5577: # start: timestamp
                   5578: # end: timestamp
                   5579: #
1.240     www      5580:     my (%filters)=@_;
1.620     albertel 5581:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5582:     if ($filters{'url'}) {
                   5583: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5584:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5585:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5586:     }
1.620     albertel 5587:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5588:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5589:     return &log_query($cname,$cdom,'courselog',%filters);
                   5590: }
                   5591: 
                   5592: sub userlog_query {
1.858     raeburn  5593: #
                   5594: # possible filters:
                   5595: # action: log check role
                   5596: # start: timestamp
                   5597: # end: timestamp
                   5598: #
1.240     www      5599:     my ($uname,$udom,%filters)=@_;
                   5600:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5601: }
                   5602: 
1.506     raeburn  5603: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5604: 
                   5605: sub auto_run {
1.508     raeburn  5606:     my ($cnum,$cdom) = @_;
1.876     raeburn  5607:     my $response = 0;
                   5608:     my $settings;
                   5609:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5610:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5611:         $settings = $domconfig{'autoenroll'};
                   5612:         if ($settings->{'run'} eq '1') {
                   5613:             $response = 1;
                   5614:         }
                   5615:     } else {
1.934     raeburn  5616:         my $homeserver;
                   5617:         if (&is_course($cdom,$cnum)) {
                   5618:             $homeserver = &homeserver($cnum,$cdom);
                   5619:         } else {
                   5620:             $homeserver = &domain($cdom,'primary');
                   5621:         }
                   5622:         if ($homeserver ne 'no_host') {
                   5623:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5624:         }
1.876     raeburn  5625:     }
1.506     raeburn  5626:     return $response;
                   5627: }
1.776     albertel 5628: 
1.506     raeburn  5629: sub auto_get_sections {
1.508     raeburn  5630:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5631:     my $homeserver;
                   5632:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5633:         $homeserver = &homeserver($cnum,$cdom);
                   5634:     }
                   5635:     if (!defined($homeserver)) { 
                   5636:         if ($cdom =~ /^$match_domain$/) {
                   5637:             $homeserver = &domain($cdom,'primary');
                   5638:         }
                   5639:     }
                   5640:     my @secs;
                   5641:     if (defined($homeserver)) {
                   5642:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5643:         unless ($response eq 'refused') {
                   5644:             @secs = split(/:/,$response);
                   5645:         }
1.506     raeburn  5646:     }
                   5647:     return @secs;
                   5648: }
1.776     albertel 5649: 
1.506     raeburn  5650: sub auto_new_course {
1.508     raeburn  5651:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5652:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5653:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5654:     return $response;
                   5655: }
1.776     albertel 5656: 
1.506     raeburn  5657: sub auto_validate_courseID {
1.508     raeburn  5658:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5659:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5660:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5661:     return $response;
                   5662: }
1.776     albertel 5663: 
1.1007    raeburn  5664: sub auto_validate_instcode {
1.1020    raeburn  5665:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5666:     my ($homeserver,$response);
                   5667:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5668:         $homeserver = &homeserver($cnum,$cdom);
                   5669:     }
                   5670:     if (!defined($homeserver)) {
                   5671:         if ($cdom =~ /^$match_domain$/) {
                   5672:             $homeserver = &domain($cdom,'primary');
                   5673:         }
                   5674:     }
                   5675:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020    raeburn  5676:                            &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5677:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5678:     return ($outcome,$description);
1.1007    raeburn  5679: }
                   5680: 
1.506     raeburn  5681: sub auto_create_password {
1.873     raeburn  5682:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5683:     my ($homeserver,$response);
1.506     raeburn  5684:     my $create_passwd = 0;
                   5685:     my $authchk = '';
1.873     raeburn  5686:     if ($udom =~ /^$match_domain$/) {
                   5687:         $homeserver = &domain($udom,'primary');
                   5688:     }
                   5689:     if ($homeserver eq '') {
                   5690:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5691:             $homeserver = &homeserver($cnum,$cdom);
                   5692:         }
                   5693:     }
                   5694:     if ($homeserver eq '') {
                   5695:         $authchk = 'nodomain';
1.506     raeburn  5696:     } else {
1.873     raeburn  5697:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5698:         if ($response eq 'refused') {
                   5699:             $authchk = 'refused';
                   5700:         } else {
1.901     albertel 5701:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5702:         }
1.506     raeburn  5703:     }
                   5704:     return ($authparam,$create_passwd,$authchk);
                   5705: }
                   5706: 
1.706     raeburn  5707: sub auto_photo_permission {
                   5708:     my ($cnum,$cdom,$students) = @_;
                   5709:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5710:     my ($outcome,$perm_reqd,$conditions) = 
                   5711: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5712:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5713: 	return (undef,undef);
                   5714:     }
1.706     raeburn  5715:     return ($outcome,$perm_reqd,$conditions);
                   5716: }
                   5717: 
                   5718: sub auto_checkphotos {
                   5719:     my ($uname,$udom,$pid) = @_;
                   5720:     my $homeserver = &homeserver($uname,$udom);
                   5721:     my ($result,$resulttype);
                   5722:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5723: 				   &escape($uname).':'.&escape($pid),
                   5724: 				   $homeserver));
1.709     albertel 5725:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5726: 	return (undef,undef);
                   5727:     }
1.706     raeburn  5728:     if ($outcome) {
                   5729:         ($result,$resulttype) = split(/:/,$outcome);
                   5730:     } 
                   5731:     return ($result,$resulttype);
                   5732: }
                   5733: 
                   5734: sub auto_photochoice {
                   5735:     my ($cnum,$cdom) = @_;
                   5736:     my $homeserver = &homeserver($cnum,$cdom);
                   5737:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5738: 						       &escape($cdom),
                   5739: 						       $homeserver)));
1.709     albertel 5740:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5741: 	return (undef,undef);
                   5742:     }
1.706     raeburn  5743:     return ($update,$comment);
                   5744: }
                   5745: 
                   5746: sub auto_photoupdate {
                   5747:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5748:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5749:     my $host=&hostname($homeserver);
1.706     raeburn  5750:     my $cmd = '';
                   5751:     my $maxtries = 1;
1.800     albertel 5752:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5753:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5754:     }
                   5755:     $cmd =~ s/%%$//;
                   5756:     $cmd = &escape($cmd);
                   5757:     my $query = 'institutionalphotos';
                   5758:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5759:     unless ($queryid=~/^\Q$host\E\_/) {
                   5760:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5761:         return 'error: '.$queryid;
                   5762:     }
                   5763:     my $reply = &get_query_reply($queryid);
                   5764:     my $tries = 1;
                   5765:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5766:         $reply = &get_query_reply($queryid);
                   5767:         $tries ++;
                   5768:     }
                   5769:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5770:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5771:     } else {
                   5772:         my @responses = split(/:/,$reply);
                   5773:         my $outcome = shift(@responses); 
                   5774:         foreach my $item (@responses) {
                   5775:             my ($key,$value) = split(/=/,$item);
                   5776:             $$photo{$key} = $value;
                   5777:         }
                   5778:         return $outcome;
                   5779:     }
                   5780:     return 'error';
                   5781: }
                   5782: 
1.521     raeburn  5783: sub auto_instcode_format {
1.793     albertel 5784:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5785: 	$cat_order) = @_;
1.521     raeburn  5786:     my $courses = '';
1.772     raeburn  5787:     my @homeservers;
1.521     raeburn  5788:     if ($caller eq 'global') {
1.841     albertel 5789: 	my %servers = &get_servers($codedom,'library');
                   5790: 	foreach my $tryserver (keys(%servers)) {
                   5791: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5792: 		push(@homeservers,$tryserver);
                   5793: 	    }
1.584     raeburn  5794:         }
1.1022    raeburn  5795:     } elsif ($caller eq 'requests') {
                   5796:         if ($codedom =~ /^$match_domain$/) {
                   5797:             my $chome = &domain($codedom,'primary');
                   5798:             unless ($chome eq 'no_host') {
                   5799:                 push(@homeservers,$chome);
                   5800:             }
                   5801:         }
1.521     raeburn  5802:     } else {
1.772     raeburn  5803:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5804:     }
1.793     albertel 5805:     foreach my $code (keys(%{$instcodes})) {
                   5806:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5807:     }
                   5808:     chop($courses);
1.772     raeburn  5809:     my $ok_response = 0;
                   5810:     my $response;
                   5811:     while (@homeservers > 0 && $ok_response == 0) {
                   5812:         my $server = shift(@homeservers); 
                   5813:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5814:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5815:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5816: 		split(/:/,$response);
1.772     raeburn  5817:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5818:             push(@{$codetitles},&str2array($codetitles_str));
                   5819:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5820:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5821:             $ok_response = 1;
                   5822:         }
                   5823:     }
                   5824:     if ($ok_response) {
1.521     raeburn  5825:         return 'ok';
1.772     raeburn  5826:     } else {
                   5827:         return $response;
1.521     raeburn  5828:     }
                   5829: }
                   5830: 
1.792     raeburn  5831: sub auto_instcode_defaults {
                   5832:     my ($domain,$returnhash,$code_order) = @_;
                   5833:     my @homeservers;
1.841     albertel 5834: 
                   5835:     my %servers = &get_servers($domain,'library');
                   5836:     foreach my $tryserver (keys(%servers)) {
                   5837: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5838: 	    push(@homeservers,$tryserver);
                   5839: 	}
1.792     raeburn  5840:     }
1.841     albertel 5841: 
1.792     raeburn  5842:     my $response;
1.841     albertel 5843:     foreach my $server (@homeservers) {
1.792     raeburn  5844:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5845:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5846: 	
                   5847: 	foreach my $pair (split(/\&/,$response)) {
                   5848: 	    my ($name,$value)=split(/\=/,$pair);
                   5849: 	    if ($name eq 'code_order') {
                   5850: 		@{$code_order} = split(/\&/,&unescape($value));
                   5851: 	    } else {
                   5852: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5853: 	    }
                   5854: 	}
                   5855: 	return 'ok';
1.792     raeburn  5856:     }
1.841     albertel 5857: 
                   5858:     return $response;
1.1003    raeburn  5859: }
                   5860: 
                   5861: sub auto_possible_instcodes {
1.1007    raeburn  5862:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5863:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5864:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5865:         return;
                   5866:     }
1.1003    raeburn  5867:     my (@homeservers,$uhome);
                   5868:     if (defined(&domain($domain,'primary'))) {
                   5869:         $uhome=&domain($domain,'primary');
                   5870:         push(@homeservers,&domain($domain,'primary'));
                   5871:     } else {
                   5872:         my %servers = &get_servers($domain,'library');
                   5873:         foreach my $tryserver (keys(%servers)) {
                   5874:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5875:                 push(@homeservers,$tryserver);
                   5876:             }
                   5877:         }
                   5878:     }
                   5879:     my $response;
                   5880:     foreach my $server (@homeservers) {
                   5881:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5882:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5883:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5884:             split(':',$response);
                   5885:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5886:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5887:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5888:             my ($name,$value)=split('=',$item);
                   5889:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5890:         }
                   5891:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5892:             my ($name,$value)=split('=',$item);
                   5893:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5894:         }
                   5895:         return 'ok';
                   5896:     }
                   5897:     return $response;
                   5898: }
1.792     raeburn  5899: 
1.1010    raeburn  5900: sub auto_courserequest_checks {
                   5901:     my ($dom) = @_;
1.1020    raeburn  5902:     my ($homeserver,%validations);
                   5903:     if ($dom =~ /^$match_domain$/) {
                   5904:         $homeserver = &domain($dom,'primary');
                   5905:     }
                   5906:     unless ($homeserver eq 'no_host') {
                   5907:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   5908:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   5909:             my @items = split(/&/,$response);
                   5910:             foreach my $item (@items) {
                   5911:                 my ($key,$value) = split('=',$item);
                   5912:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   5913:             }
                   5914:         }
                   5915:     }
1.1010    raeburn  5916:     return %validations; 
                   5917: }
                   5918: 
1.1020    raeburn  5919: sub auto_courserequest_validation {
                   5920:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   5921:     my ($homeserver,$response);
                   5922:     if ($dom =~ /^$match_domain$/) {
                   5923:         $homeserver = &domain($dom,'primary');
                   5924:     }
                   5925:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  5926:           
1.1020    raeburn  5927:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  5928:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  5929:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   5930:                                     $homeserver));
                   5931:     }
                   5932:     return $response;
                   5933: }
                   5934: 
1.777     albertel 5935: sub auto_validate_class_sec {
1.918     raeburn  5936:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5937:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5938:     my $ownerlist;
                   5939:     if (ref($owners) eq 'ARRAY') {
                   5940:         $ownerlist = join(',',@{$owners});
                   5941:     } else {
                   5942:         $ownerlist = $owners;
                   5943:     }
1.773     raeburn  5944:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5945:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5946:     return $response;
                   5947: }
                   5948: 
1.679     raeburn  5949: # ------------------------------------------------------- Course Group routines
                   5950: 
                   5951: sub get_coursegroups {
1.809     raeburn  5952:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5953:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5954: }
                   5955: 
1.679     raeburn  5956: sub modify_coursegroup {
                   5957:     my ($cdom,$cnum,$groupsettings) = @_;
                   5958:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5959: }
                   5960: 
1.809     raeburn  5961: sub toggle_coursegroup_status {
                   5962:     my ($cdom,$cnum,$group,$action) = @_;
                   5963:     my ($from_namespace,$to_namespace);
                   5964:     if ($action eq 'delete') {
                   5965:         $from_namespace = 'coursegroups';
                   5966:         $to_namespace = 'deleted_groups';
                   5967:     } else {
                   5968:         $from_namespace = 'deleted_groups';
                   5969:         $to_namespace = 'coursegroups';
                   5970:     }
                   5971:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5972:     if (my $tmp = &error(%curr_group)) {
                   5973:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5974:         return ('read error',$tmp);
                   5975:     } else {
                   5976:         my %savedsettings = %curr_group; 
1.809     raeburn  5977:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5978:         my $deloutcome;
                   5979:         if ($result eq 'ok') {
1.809     raeburn  5980:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5981:         } else {
                   5982:             return ('write error',$result);
                   5983:         }
                   5984:         if ($deloutcome eq 'ok') {
                   5985:             return 'ok';
                   5986:         } else {
                   5987:             return ('delete error',$deloutcome);
                   5988:         }
                   5989:     }
                   5990: }
                   5991: 
1.679     raeburn  5992: sub modify_group_roles {
1.957     raeburn  5993:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5994:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5995:     my $role = 'gr/'.&escape($userprivs);
                   5996:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5997:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5998:     if ($result eq 'ok') {
                   5999:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6000:     }
1.679     raeburn  6001:     return $result;
                   6002: }
                   6003: 
                   6004: sub modify_coursegroup_membership {
                   6005:     my ($cdom,$cnum,$membership) = @_;
                   6006:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6007:     return $result;
                   6008: }
                   6009: 
1.682     raeburn  6010: sub get_active_groups {
                   6011:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6012:     my $now = time;
                   6013:     my %groups = ();
                   6014:     foreach my $key (keys(%env)) {
1.811     albertel 6015:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6016:             my ($start,$end) = split(/\./,$env{$key});
                   6017:             if (($end!=0) && ($end<$now)) { next; }
                   6018:             if (($start!=0) && ($start>$now)) { next; }
                   6019:             if ($1 eq $cdom && $2 eq $cnum) {
                   6020:                 $groups{$3} = $env{$key} ;
                   6021:             }
                   6022:         }
                   6023:     }
                   6024:     return %groups;
                   6025: }
                   6026: 
1.683     raeburn  6027: sub get_group_membership {
                   6028:     my ($cdom,$cnum,$group) = @_;
                   6029:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6030: }
                   6031: 
                   6032: sub get_users_groups {
                   6033:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6034:     my @usersgroups;
1.683     raeburn  6035:     my $cachetime=1800;
                   6036: 
                   6037:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6038:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6039:     if (defined($cached)) {
1.734     albertel 6040:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6041:     } else {  
                   6042:         $grouplist = '';
1.816     raeburn  6043:         my $courseurl = &courseid_to_courseurl($courseid);
                   6044:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6045:         my $access_end = $env{'course.'.$courseid.
                   6046:                               '.default_enrollment_end_date'};
                   6047:         my $now = time;
                   6048:         foreach my $key (keys(%roleshash)) {
                   6049:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6050:                 my $group = $1;
                   6051:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6052:                     my $start = $2;
                   6053:                     my $end = $1;
                   6054:                     if ($start == -1) { next; } # deleted from group
                   6055:                     if (($start!=0) && ($start>$now)) { next; }
                   6056:                     if (($end!=0) && ($end<$now)) {
                   6057:                         if ($access_end && $access_end < $now) {
                   6058:                             if ($access_end - $end < 86400) {
                   6059:                                 push(@usersgroups,$group);
1.733     raeburn  6060:                             }
                   6061:                         }
1.817     raeburn  6062:                         next;
1.733     raeburn  6063:                     }
1.817     raeburn  6064:                     push(@usersgroups,$group);
1.683     raeburn  6065:                 }
                   6066:             }
                   6067:         }
1.817     raeburn  6068:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6069:         $grouplist = join(':',@usersgroups);
                   6070:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6071:     }
1.733     raeburn  6072:     return @usersgroups;
1.683     raeburn  6073: }
                   6074: 
                   6075: sub devalidate_getgroups_cache {
                   6076:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6077:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6078: 
1.683     raeburn  6079:     my $hashid="$udom:$uname:$courseid";
                   6080:     &devalidate_cache_new('getgroups',$hashid);
                   6081: }
                   6082: 
1.12      www      6083: # ------------------------------------------------------------------ Plain Text
                   6084: 
                   6085: sub plaintext {
1.988     raeburn  6086:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 6087:     if ($short =~ /^cr/) {
                   6088: 	return (split('/',$short))[-1];
                   6089:     }
1.742     raeburn  6090:     if (!defined($cid)) {
                   6091:         $cid = $env{'request.course.id'};
                   6092:     }
                   6093:     my %rolenames = (
1.1008    raeburn  6094:                       Course    => 'std',
                   6095:                       Community => 'alt1',
1.742     raeburn  6096:                     );
1.1037    raeburn  6097:     if ($cid ne '') {
                   6098:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6099:             unless ($forcedefault) {
                   6100:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6101:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6102:                 return &Apache::lonlocal::mt($roletext);
                   6103:             }
                   6104:         }
                   6105:     }
                   6106:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6107:         (defined($rolenames{$type})) && 
                   6108:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6109:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6110:     } elsif ($cid ne '') {
                   6111:         my $crstype = $env{'course.'.$cid.'.type'};
                   6112:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6113:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6114:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6115:         }
1.742     raeburn  6116:     }
1.1037    raeburn  6117:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6118: }
                   6119: 
                   6120: # ----------------------------------------------------------------- Assign Role
                   6121: 
                   6122: sub assignrole {
1.957     raeburn  6123:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6124:         $context)=@_;
1.21      www      6125:     my $mrole;
                   6126:     if ($role =~ /^cr\//) {
1.393     www      6127:         my $cwosec=$url;
1.811     albertel 6128:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6129: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6130:            my $refused = 1;
                   6131:            if ($context eq 'requestcourses') {
                   6132:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6133:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6134:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6135:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6136:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6137:                            if ($crsenv{'internal.courseowner'} eq
                   6138:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6139:                                $refused = '';
                   6140:                            }
                   6141:                        }
                   6142:                    }
                   6143:                }
                   6144:            }
                   6145:            if ($refused) {
                   6146:                &logthis('Refused custom assignrole: '.
                   6147:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6148:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6149:                return 'refused';
                   6150:            }
1.104     www      6151:         }
1.21      www      6152:         $mrole='cr';
1.678     raeburn  6153:     } elsif ($role =~ /^gr\//) {
                   6154:         my $cwogrp=$url;
1.811     albertel 6155:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6156:         unless (&allowed('mdg',$cwogrp)) {
                   6157:             &logthis('Refused group assignrole: '.
                   6158:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6159:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6160:             return 'refused';
                   6161:         }
                   6162:         $mrole='gr';
1.21      www      6163:     } else {
1.82      www      6164:         my $cwosec=$url;
1.811     albertel 6165:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6166:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6167:             my $refused;
                   6168:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6169:                 if (!(&allowed('c'.$role,$url))) {
                   6170:                     $refused = 1;
                   6171:                 }
                   6172:             } else {
                   6173:                 $refused = 1;
                   6174:             }
1.947     raeburn  6175:             if ($refused) {
                   6176:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6177:                     $refused = '';
1.1017    raeburn  6178:                 } elsif ($context eq 'requestcourses') {
1.1026    raeburn  6179:                     my @possroles = ('st','ta','ep','in','cc');
                   6180:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
                   6181:                         my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1017    raeburn  6182:                         my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6183:                         if ($crsenv{'internal.courseowner'} eq 
                   6184:                              $env{'user.name'}.':'.$env{'user.domain'}) {
                   6185:                             $refused = '';
                   6186:                         }
                   6187:                     }
                   6188:                 }
                   6189:                 if ($refused) {
1.947     raeburn  6190:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6191:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6192: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6193:                     return 'refused';
                   6194:                 }
1.932     raeburn  6195:             }
1.104     www      6196:         }
1.21      www      6197:         $mrole=$role;
                   6198:     }
1.620     albertel 6199:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6200:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6201:     if ($end) { $command.='_'.$end; }
1.21      www      6202:     if ($start) {
                   6203: 	if ($end) { 
1.81      www      6204:            $command.='_'.$start; 
1.21      www      6205:         } else {
1.81      www      6206:            $command.='_0_'.$start;
1.21      www      6207:         }
                   6208:     }
1.739     raeburn  6209:     my $origstart = $start;
                   6210:     my $origend = $end;
1.957     raeburn  6211:     my $delflag;
1.357     www      6212: # actually delete
                   6213:     if ($deleteflag) {
1.373     www      6214: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6215: # modify command to delete the role
1.620     albertel 6216:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6217:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6218: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6219: # set start and finish to negative values for userrolelog
                   6220:            $start=-1;
                   6221:            $end=-1;
1.957     raeburn  6222:            $delflag = 1;
1.357     www      6223:         }
                   6224:     }
                   6225: # send command
1.349     www      6226:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6227: # log new user role if status is ok
1.349     www      6228:     if ($answer eq 'ok') {
1.663     raeburn  6229: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6230: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6231:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6232:         unless ($role =~ /^gr/) {
                   6233:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6234:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6235:         }
1.349     www      6236:     }
                   6237:     return $answer;
1.169     harris41 6238: }
                   6239: 
                   6240: # -------------------------------------------------- Modify user authentication
1.197     www      6241: # Overrides without validation
                   6242: 
1.169     harris41 6243: sub modifyuserauth {
                   6244:     my ($udom,$uname,$umode,$upass)=@_;
                   6245:     my $uhome=&homeserver($uname,$udom);
1.197     www      6246:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6247:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6248:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6249:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6250:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6251: 		     &escape($upass),$uhome);
1.620     albertel 6252:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6253:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6254:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6255:     &log($udom,,$uname,$uhome,
1.620     albertel 6256:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6257:                                      $env{'user.name'}.', '.$umode.
1.197     www      6258:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6259:     unless ($reply eq 'ok') {
1.197     www      6260:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6261: 	return 'error: '.$reply;
                   6262:     }   
1.170     harris41 6263:     return 'ok';
1.80      www      6264: }
                   6265: 
1.81      www      6266: # --------------------------------------------------------------- Modify a user
1.80      www      6267: 
1.81      www      6268: sub modifyuser {
1.206     matthew  6269:     my ($udom,    $uname, $uid,
                   6270:         $umode,   $upass, $first,
                   6271:         $middle,  $last,  $gene,
1.963     raeburn  6272:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6273:     $udom= &LONCAPA::clean_domain($udom);
                   6274:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6275:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6276:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6277: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6278:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6279:                                      ' desiredhome not specified'). 
1.620     albertel 6280:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6281:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6282:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6283: # ----------------------------------------------------------------- Create User
1.406     albertel 6284:     if (($uhome eq 'no_host') && 
                   6285: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6286:         my $unhome='';
1.844     albertel 6287:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6288:             $unhome = $desiredhome;
1.620     albertel 6289: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6290: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6291:         } else { # load balancing routine for determining $unhome
1.81      www      6292:             my $loadm=10000000;
1.841     albertel 6293: 	    my %servers = &get_servers($udom,'library');
                   6294: 	    foreach my $tryserver (keys(%servers)) {
                   6295: 		my $answer=reply('load',$tryserver);
                   6296: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6297: 		    $loadm=$answer;
                   6298: 		    $unhome=$tryserver;
                   6299: 		}
1.80      www      6300: 	    }
                   6301:         }
                   6302:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6303: 	    return 'error: unable to find a home server for '.$uname.
                   6304:                    ' in domain '.$udom;
1.80      www      6305:         }
                   6306:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6307:                          &escape($upass),$unhome);
                   6308: 	unless ($reply eq 'ok') {
                   6309:             return 'error: '.$reply;
                   6310:         }   
1.230     stredwic 6311:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6312:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6313: 	    return 'error: unable verify users home machine.';
1.80      www      6314:         }
1.209     matthew  6315:     }   # End of creation of new user
1.80      www      6316: # ---------------------------------------------------------------------- Add ID
                   6317:     if ($uid) {
                   6318:        $uid=~tr/A-Z/a-z/;
                   6319:        my %uidhash=&idrget($udom,$uname);
1.196     www      6320:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6321:          && (!$forceid)) {
1.80      www      6322: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6323: 	      return 'error: user id "'.$uid.'" does not match '.
                   6324:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6325:           }
                   6326:        } else {
                   6327: 	  &idput($udom,($uname => $uid));
                   6328:        }
                   6329:     }
                   6330: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6331:     my @tmp=&get('environment',
1.899     raeburn  6332: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6333:                     'permanentemail','inststatus'],
1.134     albertel 6334: 		   $udom,$uname);
1.313     matthew  6335:     my %names;
                   6336:     if ($tmp[0] =~ m/^error:.*/) { 
                   6337:         %names=(); 
                   6338:     } else {
                   6339:         %names = @tmp;
                   6340:     }
1.388     www      6341: #
                   6342: # Make sure to not trash student environment if instructor does not bother
                   6343: # to supply name and email information
                   6344: #
                   6345:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6346:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6347:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6348:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6349:     if ($email) {
                   6350:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6351:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6352:     }
1.899     raeburn  6353:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6354:     if (defined($inststatus)) {
                   6355:         $names{'inststatus'} = '';
                   6356:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6357:         if (ref($usertypes) eq 'HASH') {
                   6358:             my @okstatuses; 
                   6359:             foreach my $item (split(/:/,$inststatus)) {
                   6360:                 if (defined($usertypes->{$item})) {
                   6361:                     push(@okstatuses,$item);  
                   6362:                 }
                   6363:             }
                   6364:             if (@okstatuses) {
                   6365:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6366:             }
                   6367:         }
                   6368:     }
1.134     albertel 6369:     my $reply = &put('environment', \%names, $udom,$uname);
                   6370:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6371:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6372:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6373:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6374:                  $umode.', '.$first.', '.$middle.', '.
                   6375: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6376:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6377:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6378:     } else {
                   6379:         $logmsg .= ' during self creation';
                   6380:     }
                   6381:     &logthis($logmsg);
1.134     albertel 6382:     return 'ok';
1.80      www      6383: }
                   6384: 
1.81      www      6385: # -------------------------------------------------------------- Modify student
1.80      www      6386: 
1.81      www      6387: sub modifystudent {
                   6388:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6389:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6390:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6391:     if (!$cid) {
1.620     albertel 6392: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6393: 	    return 'not_in_class';
                   6394: 	}
1.80      www      6395:     }
                   6396: # --------------------------------------------------------------- Make the user
1.81      www      6397:     my $reply=&modifyuser
1.209     matthew  6398: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6399:          $desiredhome,$email,$inststatus);
1.80      www      6400:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6401:     # This will cause &modify_student_enrollment to get the uid from the
                   6402:     # students environment
                   6403:     $uid = undef if (!$forceid);
1.455     albertel 6404:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6405: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6406:     return $reply;
                   6407: }
                   6408: 
                   6409: sub modify_student_enrollment {
1.957     raeburn  6410:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6411:     my ($cdom,$cnum,$chome);
                   6412:     if (!$cid) {
1.620     albertel 6413: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6414: 	    return 'not_in_class';
                   6415: 	}
1.620     albertel 6416: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6417: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6418:     } else {
                   6419: 	($cdom,$cnum)=split(/_/,$cid);
                   6420:     }
1.620     albertel 6421:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6422:     if (!$chome) {
1.457     raeburn  6423: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6424:     }
1.455     albertel 6425:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6426:     # Make sure the user exists
1.81      www      6427:     my $uhome=&homeserver($uname,$udom);
                   6428:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6429: 	return 'error: no such user';
                   6430:     }
1.297     matthew  6431:     # Get student data if we were not given enough information
                   6432:     if (!defined($first)  || $first  eq '' || 
                   6433:         !defined($last)   || $last   eq '' || 
                   6434:         !defined($uid)    || $uid    eq '' || 
                   6435:         !defined($middle) || $middle eq '' || 
                   6436:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6437:         # They did not supply us with enough data to enroll the student, so
                   6438:         # we need to pick up more information.
1.297     matthew  6439:         my %tmp = &get('environment',
1.294     matthew  6440:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6441:                        ,$udom,$uname);
                   6442: 
1.800     albertel 6443:         #foreach my $key (keys(%tmp)) {
                   6444:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6445:         #}
1.294     matthew  6446:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6447:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6448:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6449:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6450:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6451:     }
1.556     albertel 6452:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6453:     my $reply=cput('classlist',
                   6454: 		   {"$uname:$udom" => 
1.515     raeburn  6455: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6456: 		   $cdom,$cnum);
1.81      www      6457:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6458: 	return 'error: '.$reply;
1.652     albertel 6459:     } else {
                   6460: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6461:     }
1.297     matthew  6462:     # Add student role to user
1.83      www      6463:     my $uurl='/'.$cid;
1.81      www      6464:     $uurl=~s/\_/\//g;
                   6465:     if ($usec) {
                   6466: 	$uurl.='/'.$usec;
                   6467:     }
1.957     raeburn  6468:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6469: }
                   6470: 
1.556     albertel 6471: sub format_name {
                   6472:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6473:     my $name;
                   6474:     if ($first ne 'lastname') {
                   6475: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6476:     } else {
                   6477: 	if ($lastname=~/\S/) {
                   6478: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6479: 	    $name=~s/\s+,/,/;
                   6480: 	} else {
                   6481: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6482: 	}
                   6483:     }
                   6484:     $name=~s/^\s+//;
                   6485:     $name=~s/\s+$//;
                   6486:     $name=~s/\s+/ /g;
                   6487:     return $name;
                   6488: }
                   6489: 
1.84      www      6490: # ------------------------------------------------- Write to course preferences
                   6491: 
                   6492: sub writecoursepref {
                   6493:     my ($courseid,%prefs)=@_;
                   6494:     $courseid=~s/^\///;
                   6495:     $courseid=~s/\_/\//g;
                   6496:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6497:     my $chome=homeserver($cnum,$cdomain);
                   6498:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6499: 	return 'error: no such course';
                   6500:     }
                   6501:     my $cstring='';
1.800     albertel 6502:     foreach my $pref (keys(%prefs)) {
                   6503: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6504:     }
1.84      www      6505:     $cstring=~s/\&$//;
                   6506:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6507: }
                   6508: 
                   6509: # ---------------------------------------------------------- Make/modify course
                   6510: 
                   6511: sub createcourse {
1.741     raeburn  6512:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6513:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6514:     $url=&declutter($url);
                   6515:     my $cid='';
1.1028    raeburn  6516:     if ($context eq 'requestcourses') {
                   6517:         my $can_create = 0;
                   6518:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6519:         if ($udom eq $ownerdom) {
                   6520:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6521:                                   $context)) {
                   6522:                 $can_create = 1;
                   6523:             }
                   6524:         } else {
                   6525:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6526:                                            $category);
                   6527:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6528:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6529:                 if (@curr > 0) {
                   6530:                     my @options = qw(approval validate autolimit);
                   6531:                     my $optregex = join('|',@options);
                   6532:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6533:                         $can_create = 1;
                   6534:                     }
                   6535:                 }
                   6536:             }
                   6537:         }
                   6538:         if ($can_create) {
                   6539:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   6540:                 unless (&allowed('ccc',$udom)) {
                   6541:                     return 'refused'; 
                   6542:                 }
1.1017    raeburn  6543:             }
                   6544:         } else {
                   6545:             return 'refused';
                   6546:         }
1.1028    raeburn  6547:     } elsif (!&allowed('ccc',$udom)) {
                   6548:         return 'refused';
1.84      www      6549:     }
1.1011    raeburn  6550: # --------------------------------------------------------------- Get Unique ID
                   6551:     my $uname;
                   6552:     if ($cnum =~ /^$match_courseid$/) {
                   6553:         my $chome=&homeserver($cnum,$udom,'true');
                   6554:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6555:             $uname = $cnum;
                   6556:         } else {
1.1038  ! raeburn  6557:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6558:         }
                   6559:     } else {
1.1038  ! raeburn  6560:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6561:     }
                   6562:     return $uname if ($uname =~ /^error/);
                   6563: # -------------------------------------------------- Check supplied server name
1.620     albertel 6564:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6565:     if (! &is_library($course_server)) {
1.264     matthew  6566:         return 'error:bad server name '.$course_server;
                   6567:     }
1.84      www      6568: # ------------------------------------------------------------- Make the course
                   6569:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6570:                       $course_server);
1.84      www      6571:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6572:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6573:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6574: 	return 'error: no such course';
                   6575:     }
1.271     www      6576: # ----------------------------------------------------------------- Course made
1.516     raeburn  6577: # log existence
1.1029    raeburn  6578:     my $now = time;
1.918     raeburn  6579:     my $newcourse = {
                   6580:                     $udom.'_'.$uname => {
1.921     raeburn  6581:                                      description => $description,
                   6582:                                      inst_code   => $inst_code,
                   6583:                                      owner       => $course_owner,
                   6584:                                      type        => $crstype,
1.1029    raeburn  6585:                                      creator     => $env{'user.name'}.':'.
                   6586:                                                     $env{'user.domain'},
                   6587:                                      created     => $now,
                   6588:                                      context     => $context,
1.918     raeburn  6589:                                                 },
                   6590:                     };
1.921     raeburn  6591:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6592: # set toplevel url
1.271     www      6593:     my $topurl=$url;
                   6594:     unless ($nonstandard) {
                   6595: # ------------------------------------------ For standard courses, make top url
                   6596:         my $mapurl=&clutter($url);
1.278     www      6597:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6598:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6599: <map>
                   6600: <resource id="1" type="start"></resource>
                   6601: <resource id="2" src="$mapurl"></resource>
                   6602: <resource id="3" type="finish"></resource>
                   6603: <link index="1" from="1" to="2"></link>
                   6604: <link index="2" from="2" to="3"></link>
                   6605: </map>
                   6606: ENDINITMAP
                   6607:         $topurl=&declutter(
1.638     albertel 6608:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6609:                           );
                   6610:     }
                   6611: # ----------------------------------------------------------- Write preferences
1.84      www      6612:     &writecoursepref($udom.'_'.$uname,
                   6613:                      ('description' => $description,
1.271     www      6614:                       'url'         => $topurl));
1.84      www      6615:     return '/'.$udom.'/'.$uname;
                   6616: }
                   6617: 
1.1011    raeburn  6618: # ------------------------------------------------------------------- Create ID
                   6619: sub generate_coursenum {
1.1038  ! raeburn  6620:     my ($udom,$crstype) = @_;
1.1011    raeburn  6621:     my $domdesc = &domain($udom);
                   6622:     return 'error: invalid domain' if ($domdesc eq '');
1.1038  ! raeburn  6623:     my $first;
        !          6624:     if ($crstype eq 'Community') {
        !          6625:         $first = '0';
        !          6626:     } else {
        !          6627:         $first = int(1+rand(9)); 
        !          6628:     } 
        !          6629:     my $uname=$first.
1.1011    raeburn  6630:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6631:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6632:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6633: # ----------------------------------------------- Make sure that does not exist
                   6634:     my $uhome=&homeserver($uname,$udom,'true');
                   6635:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038  ! raeburn  6636:         if ($crstype eq 'Community') {
        !          6637:             $first = '0';
        !          6638:         } else {
        !          6639:             $first = int(1+rand(9));
        !          6640:         }
        !          6641:         $uname=$first.
1.1011    raeburn  6642:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6643:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6644:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6645:         $uhome=&homeserver($uname,$udom,'true');
                   6646:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6647:             return 'error: unable to generate unique course-ID';
                   6648:         }
                   6649:     }
                   6650:     return $uname;
                   6651: }
                   6652: 
1.813     albertel 6653: sub is_course {
                   6654:     my ($cdom,$cnum) = @_;
                   6655:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6656: 				undef,'.');
1.813     albertel 6657:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6658:         return 1;
                   6659:     }
                   6660:     return 0;
                   6661: }
                   6662: 
1.1015    raeburn  6663: sub store_userdata {
                   6664:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  6665:     my $result;
1.1016    raeburn  6666:     if ($datakey ne '') {
1.1013    raeburn  6667:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  6668:             if ($udom eq '' || $uname eq '') {
                   6669:                 $udom = $env{'user.domain'};
                   6670:                 $uname = $env{'user.name'};
                   6671:             }
                   6672:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  6673:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   6674:                 $result = 'error: no_host';
                   6675:             } else {
                   6676:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   6677:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   6678: 
                   6679:                 my $namevalue='';
                   6680:                 foreach my $key (keys(%{$storehash})) {
                   6681:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6682:                 }
                   6683:                 $namevalue=~s/\&$//;
                   6684:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  6685:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  6686:             }
                   6687:         } else {
                   6688:             $result = 'error: data to store was not a hash reference'; 
                   6689:         }
                   6690:     } else {
                   6691:         $result= 'error: invalid requestkey'; 
                   6692:     }
                   6693:     return $result;
                   6694: }
                   6695: 
1.21      www      6696: # ---------------------------------------------------------- Assign Custom Role
                   6697: 
                   6698: sub assigncustomrole {
1.957     raeburn  6699:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6700:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6701:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6702: }
                   6703: 
                   6704: # ----------------------------------------------------------------- Revoke Role
                   6705: 
                   6706: sub revokerole {
1.957     raeburn  6707:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6708:     my $now=time;
1.965     raeburn  6709:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6710: }
                   6711: 
                   6712: # ---------------------------------------------------------- Revoke Custom Role
                   6713: 
                   6714: sub revokecustomrole {
1.957     raeburn  6715:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6716:     my $now=time;
1.357     www      6717:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6718:            $deleteflag,$selfenroll,$context);
1.17      www      6719: }
                   6720: 
1.533     banghart 6721: # ------------------------------------------------------------ Disk usage
1.535     albertel 6722: sub diskusage {
1.955     raeburn  6723:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6724:     $directorypath =~ s/\/$//;
                   6725:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6726:                        .&escape($getpropath).':'.&escape($uname).':'
                   6727:                        .&escape($udom),homeserver($uname,$udom));
                   6728:     if ($listing eq 'unknown_cmd') {
                   6729:         if ($getpropath) {
                   6730:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6731:         }
                   6732:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6733:     }
1.514     albertel 6734:     return $listing;
1.512     banghart 6735: }
                   6736: 
1.566     banghart 6737: sub is_locked {
                   6738:     my ($file_name, $domain, $user) = @_;
                   6739:     my @check;
                   6740:     my $is_locked;
                   6741:     push @check, $file_name;
1.613     albertel 6742:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6743: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6744:     my ($tmp)=keys(%locked);
                   6745:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6746:     
1.566     banghart 6747:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6748:         $is_locked = 'false';
                   6749:         foreach my $entry (@{$locked{$file_name}}) {
                   6750:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6751:                $is_locked = 'true';
                   6752:                last;
1.745     raeburn  6753:            }
                   6754:        }
1.566     banghart 6755:     } else {
                   6756:         $is_locked = 'false';
                   6757:     }
                   6758: }
                   6759: 
1.759     albertel 6760: sub declutter_portfile {
                   6761:     my ($file) = @_;
1.833     albertel 6762:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6763:     return $file;
                   6764: }
                   6765: 
1.559     banghart 6766: # ------------------------------------------------------------- Mark as Read Only
                   6767: 
                   6768: sub mark_as_readonly {
                   6769:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6770:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6771:     my ($tmp)=keys(%current_permissions);
                   6772:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6773:     foreach my $file (@{$files}) {
1.759     albertel 6774: 	$file = &declutter_portfile($file);
1.561     banghart 6775:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6776:     }
1.613     albertel 6777:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6778:     return;
                   6779: }
                   6780: 
1.572     banghart 6781: # ------------------------------------------------------------Save Selected Files
                   6782: 
                   6783: sub save_selected_files {
                   6784:     my ($user, $path, @files) = @_;
                   6785:     my $filename = $user."savedfiles";
1.573     banghart 6786:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6787:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6788:     foreach my $file (@files) {
1.620     albertel 6789:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6790:     }
                   6791:     foreach my $file (@other_files) {
1.574     banghart 6792:         print (OUT $file."\n");
1.572     banghart 6793:     }
1.574     banghart 6794:     close (OUT);
1.572     banghart 6795:     return 'ok';
                   6796: }
                   6797: 
1.574     banghart 6798: sub clear_selected_files {
                   6799:     my ($user) = @_;
                   6800:     my $filename = $user."savedfiles";
                   6801:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6802:     print (OUT undef);
                   6803:     close (OUT);
                   6804:     return ("ok");    
                   6805: }
                   6806: 
1.572     banghart 6807: sub files_in_path {
                   6808:     my ($user, $path) = @_;
                   6809:     my $filename = $user."savedfiles";
                   6810:     my %return_files;
1.574     banghart 6811:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6812:     while (my $line_in = <IN>) {
1.574     banghart 6813:         chomp ($line_in);
                   6814:         my @paths_and_file = split (m!/!, $line_in);
                   6815:         my $file_part = pop (@paths_and_file);
                   6816:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6817:         $path_part.='/';
                   6818:         my $path_and_file = $path_part.$file_part;
                   6819:         if ($path_part eq $path) {
                   6820:             $return_files{$file_part}= 'selected';
                   6821:         }
                   6822:     }
1.574     banghart 6823:     close (IN);
                   6824:     return (\%return_files);
1.572     banghart 6825: }
                   6826: 
                   6827: # called in portfolio select mode, to show files selected NOT in current directory
                   6828: sub files_not_in_path {
                   6829:     my ($user, $path) = @_;
                   6830:     my $filename = $user."savedfiles";
                   6831:     my @return_files;
                   6832:     my $path_part;
1.800     albertel 6833:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6834:     while (my $line = <IN>) {
1.572     banghart 6835:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6836:         my @paths_and_file = split(m|/|, $line);
                   6837:         my $file_part = pop(@paths_and_file);
                   6838:         chomp($file_part);
                   6839:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6840:         $path_part .= '/';
                   6841:         my $path_and_file = $path_part.$file_part;
                   6842:         if ($path_part ne $path) {
1.800     albertel 6843:             push(@return_files, ($path_and_file));
1.572     banghart 6844:         }
                   6845:     }
1.800     albertel 6846:     close(OUT);
1.574     banghart 6847:     return (@return_files);
1.572     banghart 6848: }
                   6849: 
1.745     raeburn  6850: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6851: 
1.745     raeburn  6852: sub get_portfile_permissions {
                   6853:     my ($domain,$user) = @_;
1.613     albertel 6854:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6855:     my ($tmp)=keys(%current_permissions);
                   6856:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6857:     return \%current_permissions;
                   6858: }
                   6859: 
                   6860: #---------------------------------------------Get portfolio file access controls
                   6861: 
1.749     raeburn  6862: sub get_access_controls {
1.745     raeburn  6863:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6864:     my %access;
                   6865:     my $real_file = $file;
                   6866:     $file =~ s/\.meta$//;
1.745     raeburn  6867:     if (defined($file)) {
1.749     raeburn  6868:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6869:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6870:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6871:             }
                   6872:         }
1.745     raeburn  6873:     } else {
1.749     raeburn  6874:         foreach my $key (keys(%{$current_permissions})) {
                   6875:             if ($key =~ /\0accesscontrol$/) {
                   6876:                 if (defined($group)) {
                   6877:                     if ($key !~ m-^\Q$group\E/-) {
                   6878:                         next;
                   6879:                     }
                   6880:                 }
                   6881:                 my ($fullpath) = split(/\0/,$key);
                   6882:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6883:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6884:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6885:                     }
                   6886:                 }
                   6887:             }
                   6888:         }
                   6889:     }
                   6890:     return %access;
                   6891: }
                   6892: 
                   6893: sub modify_access_controls {
                   6894:     my ($file_name,$changes,$domain,$user)=@_;
                   6895:     my ($outcome,$deloutcome);
                   6896:     my %store_permissions;
                   6897:     my %new_values;
                   6898:     my %new_control;
                   6899:     my %translation;
                   6900:     my @deletions = ();
                   6901:     my $now = time;
                   6902:     if (exists($$changes{'activate'})) {
                   6903:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6904:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6905:             my $numnew = scalar(@newitems);
                   6906:             for (my $i=0; $i<$numnew; $i++) {
                   6907:                 my $newkey = $newitems[$i];
                   6908:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6909:                 if ($newkey =~ /^\d+:/) { 
                   6910:                     $newkey =~ s/^(\d+)/$newid/;
                   6911:                     $translation{$1} = $newid;
                   6912:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6913:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6914:                     $translation{$1} = $newid;
                   6915:                 }
1.749     raeburn  6916:                 $new_values{$file_name."\0".$newkey} = 
                   6917:                                           $$changes{'activate'}{$newitems[$i]};
                   6918:                 $new_control{$newkey} = $now;
                   6919:             }
                   6920:         }
                   6921:     }
                   6922:     my %todelete;
                   6923:     my %changed_items;
                   6924:     foreach my $action ('delete','update') {
                   6925:         if (exists($$changes{$action})) {
                   6926:             if (ref($$changes{$action}) eq 'HASH') {
                   6927:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6928:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6929:                     if ($action eq 'delete') { 
                   6930:                         $todelete{$itemnum} = 1;
                   6931:                     } else {
                   6932:                         $changed_items{$itemnum} = $key;
                   6933:                     }
                   6934:                 }
1.745     raeburn  6935:             }
                   6936:         }
1.749     raeburn  6937:     }
                   6938:     # get lock on access controls for file.
                   6939:     my $lockhash = {
                   6940:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6941:                                                        ':'.$env{'user.domain'},
                   6942:                    }; 
                   6943:     my $tries = 0;
                   6944:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6945:    
                   6946:     while (($gotlock ne 'ok') && $tries <3) {
                   6947:         $tries ++;
                   6948:         sleep 1;
                   6949:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6950:     }
                   6951:     if ($gotlock eq 'ok') {
                   6952:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6953:         my ($tmp)=keys(%curr_permissions);
                   6954:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6955:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6956:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6957:             if (ref($curr_controls) eq 'HASH') {
                   6958:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6959:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6960:                     if (defined($todelete{$itemnum})) {
                   6961:                         push(@deletions,$file_name."\0".$control_item);
                   6962:                     } else {
                   6963:                         if (defined($changed_items{$itemnum})) {
                   6964:                             $new_control{$changed_items{$itemnum}} = $now;
                   6965:                             push(@deletions,$file_name."\0".$control_item);
                   6966:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6967:                         } else {
                   6968:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6969:                         }
                   6970:                     }
1.745     raeburn  6971:                 }
                   6972:             }
                   6973:         }
1.970     raeburn  6974:         my ($group);
                   6975:         if (&is_course($domain,$user)) {
                   6976:             ($group,my $file) = split(/\//,$file_name,2);
                   6977:         }
1.749     raeburn  6978:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6979:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6980:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6981:         #  remove lock
                   6982:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6983:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6984:         my $sqlresult =
1.970     raeburn  6985:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6986:                                     $group);
1.749     raeburn  6987:     } else {
                   6988:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6989:     }
1.749     raeburn  6990:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6991: }
                   6992: 
1.827     raeburn  6993: sub make_public_indefinitely {
                   6994:     my ($requrl) = @_;
                   6995:     my $now = time;
                   6996:     my $action = 'activate';
                   6997:     my $aclnum = 0;
                   6998:     if (&is_portfolio_url($requrl)) {
                   6999:         my (undef,$udom,$unum,$file_name,$group) =
                   7000:             &parse_portfolio_url($requrl);
                   7001:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7002:         my %access_controls = &get_access_controls($current_perms,
                   7003:                                                    $group,$file_name);
                   7004:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7005:             my ($num,$scope,$end,$start) = 
                   7006:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7007:             if ($scope eq 'public') {
                   7008:                 if ($start <= $now && $end == 0) {
                   7009:                     $action = 'none';
                   7010:                 } else {
                   7011:                     $action = 'update';
                   7012:                     $aclnum = $num;
                   7013:                 }
                   7014:                 last;
                   7015:             }
                   7016:         }
                   7017:         if ($action eq 'none') {
                   7018:              return 'ok';
                   7019:         } else {
                   7020:             my %changes;
                   7021:             my $newend = 0;
                   7022:             my $newstart = $now;
                   7023:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7024:             $changes{$action}{$newkey} = {
                   7025:                 type => 'public',
                   7026:                 time => {
                   7027:                     start => $newstart,
                   7028:                     end   => $newend,
                   7029:                 },
                   7030:             };
                   7031:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7032:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7033:             return $outcome;
                   7034:         }
                   7035:     } else {
                   7036:         return 'invalid';
                   7037:     }
                   7038: }
                   7039: 
1.745     raeburn  7040: #------------------------------------------------------Get Marked as Read Only
                   7041: 
                   7042: sub get_marked_as_readonly {
                   7043:     my ($domain,$user,$what,$group) = @_;
                   7044:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7045:     my @readonly_files;
1.629     banghart 7046:     my $cmp1=$what;
                   7047:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7048:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7049:         if (defined($group)) {
                   7050:             if ($file_name !~ m-^\Q$group\E/-) {
                   7051:                 next;
                   7052:             }
                   7053:         }
1.561     banghart 7054:         if (ref($value) eq "ARRAY"){
                   7055:             foreach my $stored_what (@{$value}) {
1.629     banghart 7056:                 my $cmp2=$stored_what;
1.759     albertel 7057:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7058:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7059:                 }
1.629     banghart 7060:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7061:                     push(@readonly_files, $file_name);
1.745     raeburn  7062:                     last;
1.563     banghart 7063:                 } elsif (!defined($what)) {
                   7064:                     push(@readonly_files, $file_name);
1.745     raeburn  7065:                     last;
1.561     banghart 7066:                 }
                   7067:             }
1.745     raeburn  7068:         }
1.561     banghart 7069:     }
                   7070:     return @readonly_files;
                   7071: }
1.577     banghart 7072: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7073: 
1.577     banghart 7074: sub get_marked_as_readonly_hash {
1.745     raeburn  7075:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7076:     my %readonly_files;
1.745     raeburn  7077:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7078:         if (defined($group)) {
                   7079:             if ($file_name !~ m-^\Q$group\E/-) {
                   7080:                 next;
                   7081:             }
                   7082:         }
1.577     banghart 7083:         if (ref($value) eq "ARRAY"){
                   7084:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7085:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7086:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7087:                         if ($lock_descriptor eq 'graded') {
                   7088:                             $readonly_files{$file_name} = 'graded';
                   7089:                         } elsif ($lock_descriptor eq 'handback') {
                   7090:                             $readonly_files{$file_name} = 'handback';
                   7091:                         } else {
                   7092:                             if (!exists($readonly_files{$file_name})) {
                   7093:                                 $readonly_files{$file_name} = 'locked';
                   7094:                             }
                   7095:                         }
1.745     raeburn  7096:                     }
1.750     banghart 7097:                 } 
1.577     banghart 7098:             }
                   7099:         } 
                   7100:     }
                   7101:     return %readonly_files;
                   7102: }
1.559     banghart 7103: # ------------------------------------------------------------ Unmark as Read Only
                   7104: 
                   7105: sub unmark_as_readonly {
1.629     banghart 7106:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7107:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7108:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7109:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7110:     my $symb_crs = $what;
                   7111:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7112:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7113:     my ($tmp)=keys(%current_permissions);
                   7114:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7115:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7116:     foreach my $file (@readonly_files) {
1.759     albertel 7117: 	my $clean_file = &declutter_portfile($file);
                   7118: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7119: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7120:         my @new_locks;
                   7121:         my @del_keys;
                   7122:         if (ref($current_locks) eq "ARRAY"){
                   7123:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7124:                 my $compare=$locker;
1.749     raeburn  7125:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7126:                     $compare=join('',@{$locker});
1.746     raeburn  7127:                     if ($compare ne $symb_crs) {
                   7128:                         push(@new_locks, $locker);
                   7129:                     }
1.563     banghart 7130:                 }
                   7131:             }
1.650     albertel 7132:             if (scalar(@new_locks) > 0) {
1.563     banghart 7133:                 $current_permissions{$file} = \@new_locks;
                   7134:             } else {
                   7135:                 push(@del_keys, $file);
1.613     albertel 7136:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7137:                 delete($current_permissions{$file});
1.563     banghart 7138:             }
                   7139:         }
1.561     banghart 7140:     }
1.613     albertel 7141:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7142:     return;
                   7143: }
1.512     banghart 7144: 
1.17      www      7145: # ------------------------------------------------------------ Directory lister
                   7146: 
                   7147: sub dirlist {
1.955     raeburn  7148:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7149:     $uri=~s/^\///;
                   7150:     $uri=~s/\/$//;
1.253     stredwic 7151:     my ($udom, $uname);
1.955     raeburn  7152:     if ($getuserdir) {
1.253     stredwic 7153:         $udom = $userdomain;
                   7154:         $uname = $username;
1.955     raeburn  7155:     } else {
                   7156:         (undef,$udom,$uname)=split(/\//,$uri);
                   7157:         if(defined($userdomain)) {
                   7158:             $udom = $userdomain;
                   7159:         }
                   7160:         if(defined($username)) {
                   7161:             $uname = $username;
                   7162:         }
1.253     stredwic 7163:     }
1.955     raeburn  7164:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7165: 
1.955     raeburn  7166:     $dirRoot = $perlvar{'lonDocRoot'};
                   7167:     if (defined($getpropath)) {
                   7168:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7169:         $dirRoot =~ s/\/$//;
1.955     raeburn  7170:     } elsif (defined($getuserdir)) {
                   7171:         my $subdir=$uname.'__';
                   7172:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7173:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7174:                    ."/$udom/$subdir/$uname";
                   7175:     } elsif (defined($alternateRoot)) {
                   7176:         $dirRoot = $alternateRoot;
1.751     banghart 7177:     }
1.253     stredwic 7178: 
                   7179:     if($udom) {
                   7180:         if($uname) {
1.955     raeburn  7181:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7182:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7183:                               .':'.&escape($uname).':'.&escape($udom),
                   7184:                               &homeserver($uname,$udom));
                   7185:             if ($listing eq 'unknown_cmd') {
                   7186:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7187:                                   &homeserver($uname,$udom));
                   7188:             } else {
                   7189:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7190:             }
1.605     matthew  7191:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7192:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7193: 				  &homeserver($uname,$udom));
1.605     matthew  7194:                 @listing_results = split(/:/,$listing);
                   7195:             } else {
                   7196:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7197:             }
                   7198:             return @listing_results;
1.955     raeburn  7199:         } elsif(!$alternateRoot) {
1.800     albertel 7200:             my %allusers;
1.841     albertel 7201: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7202:  	    foreach my $tryserver (keys(%servers)) {
                   7203:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7204:                                   &escape($udom),$tryserver);
                   7205:                 if ($listing eq 'unknown_cmd') {
                   7206: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7207: 				      $udom, $tryserver);
                   7208:                 } else {
                   7209:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7210:                 }
1.841     albertel 7211: 		if ($listing eq 'unknown_cmd') {
                   7212: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7213: 				      $udom, $tryserver);
                   7214: 		    @listing_results = split(/:/,$listing);
                   7215: 		} else {
                   7216: 		    @listing_results =
                   7217: 			map { &unescape($_); } split(/:/,$listing);
                   7218: 		}
                   7219: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7220: 		    $listing_results[0] ne 'empty'       &&
                   7221: 		    $listing_results[0] ne 'con_lost') {
                   7222: 		    foreach my $line (@listing_results) {
                   7223: 			my ($entry) = split(/&/,$line,2);
                   7224: 			$allusers{$entry} = 1;
                   7225: 		    }
                   7226: 		}
1.253     stredwic 7227:             }
                   7228:             my $alluserstr='';
1.800     albertel 7229:             foreach my $user (sort(keys(%allusers))) {
                   7230:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7231:             }
                   7232:             $alluserstr=~s/:$//;
                   7233:             return split(/:/,$alluserstr);
                   7234:         } else {
1.800     albertel 7235:             return ('missing user name');
1.253     stredwic 7236:         }
1.955     raeburn  7237:     } elsif(!defined($getpropath)) {
1.841     albertel 7238:         my @all_domains = sort(&all_domains());
1.955     raeburn  7239:         foreach my $domain (@all_domains) {
                   7240:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7241:         }
                   7242:         return @all_domains;
                   7243:     } else {
1.800     albertel 7244:         return ('missing domain');
1.275     stredwic 7245:     }
                   7246: }
                   7247: 
                   7248: # --------------------------------------------- GetFileTimestamp
                   7249: # This function utilizes dirlist and returns the date stamp for
                   7250: # when it was last modified.  It will also return an error of -1
                   7251: # if an error occurs
                   7252: 
                   7253: sub GetFileTimestamp {
1.955     raeburn  7254:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7255:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7256:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7257:     my ($fileStat) = 
                   7258:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7259:                                  undef,$getuserdir);
1.275     stredwic 7260:     my @stats = split('&', $fileStat);
                   7261:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7262:         # @stats contains first the filename, then the stat output
                   7263:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7264:     } else {
                   7265:         return -1;
1.253     stredwic 7266:     }
1.26      www      7267: }
                   7268: 
1.712     albertel 7269: sub stat_file {
                   7270:     my ($uri) = @_;
1.787     albertel 7271:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7272: 
1.955     raeburn  7273:     my ($udom,$uname,$file);
1.712     albertel 7274:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7275: 	($udom,$uname,$file) =
1.811     albertel 7276: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7277: 	$file = 'userfiles/'.$file;
                   7278:     }
                   7279:     if ($uri =~ m-^/res/-) {
                   7280: 	($udom,$uname) = 
1.807     albertel 7281: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7282: 	$file = $uri;
                   7283:     }
                   7284: 
                   7285:     if (!$udom || !$uname || !$file) {
                   7286: 	# unable to handle the uri
                   7287: 	return ();
                   7288:     }
1.956     raeburn  7289:     my $getpropath;
                   7290:     if ($file =~ /^userfiles\//) {
                   7291:         $getpropath = 1;
                   7292:     }
1.955     raeburn  7293:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7294:     my @stats = split('&', $result);
1.721     banghart 7295:     
1.712     albertel 7296:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7297: 	shift(@stats); #filename is first
                   7298: 	return @stats;
                   7299:     }
                   7300:     return ();
                   7301: }
                   7302: 
1.26      www      7303: # -------------------------------------------------------- Value of a Condition
                   7304: 
1.713     albertel 7305: # gets the value of a specific preevaluated condition
                   7306: #    stored in the string  $env{user.state.<cid>}
                   7307: # or looks up a condition reference in the bighash and if if hasn't
                   7308: # already been evaluated recurses into docondval to get the value of
                   7309: # the condition, then memoizing it to 
                   7310: #   $env{user.state.<cid>.<condition>}
1.40      www      7311: sub directcondval {
                   7312:     my $number=shift;
1.620     albertel 7313:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7314: 	&Apache::lonuserstate::evalstate();
                   7315:     }
1.713     albertel 7316:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7317: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7318:     } elsif ($number =~ /^_/) {
                   7319: 	my $sub_condition;
                   7320: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7321: 		&GDBM_READER(),0640)) {
                   7322: 	    $sub_condition=$bighash{'conditions'.$number};
                   7323: 	    untie(%bighash);
                   7324: 	}
                   7325: 	my $value = &docondval($sub_condition);
1.949     raeburn  7326: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7327: 	return $value;
                   7328:     }
1.620     albertel 7329:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7330:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7331:     } else {
                   7332:        return 2;
                   7333:     }
                   7334: }
                   7335: 
1.713     albertel 7336: # get the collection of conditions for this resource
1.26      www      7337: sub condval {
                   7338:     my $condidx=shift;
1.54      www      7339:     my $allpathcond='';
1.713     albertel 7340:     foreach my $cond (split(/\|/,$condidx)) {
                   7341: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7342: 	    $allpathcond.=
                   7343: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7344: 	}
1.191     harris41 7345:     }
1.54      www      7346:     $allpathcond=~s/\|$//;
1.713     albertel 7347:     return &docondval($allpathcond);
                   7348: }
                   7349: 
                   7350: #evaluates an expression of conditions
                   7351: sub docondval {
                   7352:     my ($allpathcond) = @_;
                   7353:     my $result=0;
                   7354:     if ($env{'request.course.id'}
                   7355: 	&& defined($allpathcond)) {
                   7356: 	my $operand='|';
                   7357: 	my @stack;
                   7358: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7359: 	    if ($chunk eq '(') {
                   7360: 		push @stack,($operand,$result);
                   7361: 	    } elsif ($chunk eq ')') {
                   7362: 		my $before=pop @stack;
                   7363: 		if (pop @stack eq '&') {
                   7364: 		    $result=$result>$before?$before:$result;
                   7365: 		} else {
                   7366: 		    $result=$result>$before?$result:$before;
                   7367: 		}
                   7368: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7369: 		$operand=$chunk;
                   7370: 	    } else {
                   7371: 		my $new=directcondval($chunk);
                   7372: 		if ($operand eq '&') {
                   7373: 		    $result=$result>$new?$new:$result;
                   7374: 		} else {
                   7375: 		    $result=$result>$new?$result:$new;
                   7376: 		}
                   7377: 	    }
                   7378: 	}
1.26      www      7379:     }
                   7380:     return $result;
1.421     albertel 7381: }
                   7382: 
                   7383: # ---------------------------------------------------- Devalidate courseresdata
                   7384: 
                   7385: sub devalidatecourseresdata {
                   7386:     my ($coursenum,$coursedomain)=@_;
                   7387:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7388:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7389: }
                   7390: 
1.763     www      7391: 
1.200     www      7392: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7393: #
                   7394: #  Parameters:
                   7395: #      $coursenum    - Number of the course.
                   7396: #      $coursedomain - Domain at which the course was created.
                   7397: #  Returns:
                   7398: #     A hash of the course parameters along (I think) with timestamps
                   7399: #     and version info.
1.877     foxr     7400: 
1.624     albertel 7401: sub get_courseresdata {
                   7402:     my ($coursenum,$coursedomain)=@_;
1.200     www      7403:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7404:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7405:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7406:     my %dumpreply;
1.417     albertel 7407:     unless (defined($cached)) {
1.624     albertel 7408: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7409: 	$result=\%dumpreply;
1.251     albertel 7410: 	my ($tmp) = keys(%dumpreply);
                   7411: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7412: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7413: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7414: 	    return $tmp;
1.416     albertel 7415: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7416: 	    $result=undef;
1.599     albertel 7417: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7418: 	}
                   7419:     }
1.624     albertel 7420:     return $result;
                   7421: }
                   7422: 
1.633     albertel 7423: sub devalidateuserresdata {
                   7424:     my ($uname,$udom)=@_;
                   7425:     my $hashid="$udom:$uname";
                   7426:     &devalidate_cache_new('userres',$hashid);
                   7427: }
                   7428: 
1.624     albertel 7429: sub get_userresdata {
                   7430:     my ($uname,$udom)=@_;
                   7431:     #most student don\'t have any data set, check if there is some data
                   7432:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7433: 
                   7434:     my $hashid="$udom:$uname";
                   7435:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7436:     if (!defined($cached)) {
                   7437: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7438: 	$result=\%resourcedata;
                   7439: 	&do_cache_new('userres',$hashid,$result,600);
                   7440:     }
                   7441:     my ($tmp)=keys(%$result);
                   7442:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7443: 	return $result;
                   7444:     }
                   7445:     #error 2 occurs when the .db doesn't exist
                   7446:     if ($tmp!~/error: 2 /) {
1.672     albertel 7447: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7448: 		 " Trying to get resource data for ".
                   7449: 		 $uname." at ".$udom.": ".
                   7450: 		 $tmp."</font>");
                   7451:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7452: 	#&EXT_cache_set($udom,$uname);
                   7453: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7454: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7455:     }
                   7456:     return $tmp;
                   7457: }
1.879     foxr     7458: #----------------------------------------------- resdata - return resource data
                   7459: #  Purpose:
                   7460: #    Return resource data for either users or for a course.
                   7461: #  Parameters:
                   7462: #     $name      - Course/user name.
                   7463: #     $domain    - Name of the domain the user/course is registered on.
                   7464: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7465: #     @which     - Array of names of resources desired.
                   7466: #  Returns:
                   7467: #     The value of the first reasource in @which that is found in the
                   7468: #     resource hash.
                   7469: #  Exceptional Conditions:
                   7470: #     If the $type passed in is not valid (not the string 'course' or 
                   7471: #     'user', an undefined  reference is returned.
                   7472: #     If none of the resources are found, an undef is returned
1.624     albertel 7473: sub resdata {
                   7474:     my ($name,$domain,$type,@which)=@_;
                   7475:     my $result;
                   7476:     if ($type eq 'course') {
                   7477: 	$result=&get_courseresdata($name,$domain);
                   7478:     } elsif ($type eq 'user') {
                   7479: 	$result=&get_userresdata($name,$domain);
                   7480:     }
                   7481:     if (!ref($result)) { return $result; }    
1.251     albertel 7482:     foreach my $item (@which) {
1.927     albertel 7483: 	if (defined($result->{$item->[0]})) {
                   7484: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7485: 	}
1.250     albertel 7486:     }
1.291     albertel 7487:     return undef;
1.200     www      7488: }
                   7489: 
1.379     matthew  7490: #
                   7491: # EXT resource caching routines
                   7492: #
                   7493: 
                   7494: sub clear_EXT_cache_status {
1.383     albertel 7495:     &delenv('cache.EXT.');
1.379     matthew  7496: }
                   7497: 
                   7498: sub EXT_cache_status {
                   7499:     my ($target_domain,$target_user) = @_;
1.383     albertel 7500:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7501:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7502:         # We know already the user has no data
                   7503:         return 1;
                   7504:     } else {
                   7505:         return 0;
                   7506:     }
                   7507: }
                   7508: 
                   7509: sub EXT_cache_set {
                   7510:     my ($target_domain,$target_user) = @_;
1.383     albertel 7511:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7512:     #&appenv({$cachename => time});
1.379     matthew  7513: }
                   7514: 
1.28      www      7515: # --------------------------------------------------------- Value of a Variable
1.58      www      7516: sub EXT {
1.715     albertel 7517: 
1.395     albertel 7518:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7519:     unless ($varname) { return ''; }
1.218     albertel 7520:     #get real user name/domain, courseid and symb
                   7521:     my $courseid;
1.359     albertel 7522:     my $publicuser;
1.427     www      7523:     if ($symbparm) {
                   7524: 	$symbparm=&get_symb_from_alias($symbparm);
                   7525:     }
1.218     albertel 7526:     if (!($uname && $udom)) {
1.790     albertel 7527:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7528:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7529:     } else {
1.620     albertel 7530: 	$courseid=$env{'request.course.id'};
1.218     albertel 7531:     }
1.48      www      7532:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7533:     my $rest;
1.320     albertel 7534:     if (defined($therest[0])) {
1.48      www      7535:        $rest=join('.',@therest);
                   7536:     } else {
                   7537:        $rest='';
                   7538:     }
1.320     albertel 7539: 
1.57      www      7540:     my $qualifierrest=$qualifier;
                   7541:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7542:     my $spacequalifierrest=$space;
                   7543:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7544:     if ($realm eq 'user') {
1.48      www      7545: # --------------------------------------------------------------- user.resource
                   7546: 	if ($space eq 'resource') {
1.651     albertel 7547: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7548: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7549: 		 &&
1.744     albertel 7550: 		 ($symbparm eq &symbread()) ) {	
                   7551: 		# if we are in the middle of processing the resource the
                   7552: 		# get the value we are planning on committing
                   7553:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7554:                     return $Apache::lonhomework::results{$qualifierrest};
                   7555:                 } else {
                   7556:                     return $Apache::lonhomework::history{$qualifierrest};
                   7557:                 }
1.335     albertel 7558: 	    } else {
1.359     albertel 7559: 		my %restored;
1.620     albertel 7560: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7561: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7562: 		} else {
                   7563: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7564: 		}
1.335     albertel 7565: 		return $restored{$qualifierrest};
                   7566: 	    }
1.48      www      7567: # ----------------------------------------------------------------- user.access
                   7568:         } elsif ($space eq 'access') {
1.218     albertel 7569: 	    # FIXME - not supporting calls for a specific user
1.48      www      7570:             return &allowed($qualifier,$rest);
                   7571: # ------------------------------------------ user.preferences, user.environment
                   7572:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7573: 	    if (($uname eq $env{'user.name'}) &&
                   7574: 		($udom eq $env{'user.domain'})) {
                   7575: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7576: 	    } else {
1.359     albertel 7577: 		my %returnhash;
                   7578: 		if (!$publicuser) {
                   7579: 		    %returnhash=&userenvironment($udom,$uname,
                   7580: 						 $qualifierrest);
                   7581: 		}
1.218     albertel 7582: 		return $returnhash{$qualifierrest};
                   7583: 	    }
1.48      www      7584: # ----------------------------------------------------------------- user.course
                   7585:         } elsif ($space eq 'course') {
1.218     albertel 7586: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7587:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7588: # ------------------------------------------------------------------- user.role
                   7589:         } elsif ($space eq 'role') {
1.218     albertel 7590: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7591:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7592:             if ($qualifier eq 'value') {
                   7593: 		return $role;
                   7594:             } elsif ($qualifier eq 'extent') {
                   7595:                 return $where;
                   7596:             }
                   7597: # ----------------------------------------------------------------- user.domain
                   7598:         } elsif ($space eq 'domain') {
1.218     albertel 7599:             return $udom;
1.48      www      7600: # ------------------------------------------------------------------- user.name
                   7601:         } elsif ($space eq 'name') {
1.218     albertel 7602:             return $uname;
1.48      www      7603: # ---------------------------------------------------- Any other user namespace
1.29      www      7604:         } else {
1.359     albertel 7605: 	    my %reply;
                   7606: 	    if (!$publicuser) {
                   7607: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7608: 	    }
                   7609: 	    return $reply{$qualifierrest};
1.48      www      7610:         }
1.236     www      7611:     } elsif ($realm eq 'query') {
                   7612: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7613:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7614: 						[$spacequalifierrest]);
1.620     albertel 7615: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7616:    } elsif ($realm eq 'request') {
1.48      www      7617: # ------------------------------------------------------------- request.browser
                   7618:         if ($space eq 'browser') {
1.430     www      7619: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7620: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7621: 		    return 1;
                   7622: 		} else {
                   7623: 		    return 0;
                   7624: 		}
                   7625: 	    } else {
1.620     albertel 7626: 		return $env{'browser.'.$qualifier};
1.430     www      7627: 	    }
1.57      www      7628: # ------------------------------------------------------------ request.filename
                   7629:         } else {
1.620     albertel 7630:             return $env{'request.'.$spacequalifierrest};
1.29      www      7631:         }
1.28      www      7632:     } elsif ($realm eq 'course') {
1.48      www      7633: # ---------------------------------------------------------- course.description
1.620     albertel 7634:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7635:     } elsif ($realm eq 'resource') {
1.165     www      7636: 
1.620     albertel 7637: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7638: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7639: 	}
1.693     albertel 7640: 
                   7641: 	if ($space eq 'title') {
                   7642: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7643: 	    return &gettitle($symbparm);
                   7644: 	}
                   7645: 	
                   7646: 	if ($space eq 'map') {
                   7647: 	    my ($map) = &decode_symb($symbparm);
                   7648: 	    return &symbread($map);
                   7649: 	}
1.905     albertel 7650: 	if ($space eq 'filename') {
                   7651: 	    if ($symbparm) {
                   7652: 		return &clutter((&decode_symb($symbparm))[2]);
                   7653: 	    }
                   7654: 	    return &hreflocation('',$env{'request.filename'});
                   7655: 	}
1.693     albertel 7656: 
                   7657: 	my ($section, $group, @groups);
1.593     albertel 7658: 	my ($courselevelm,$courselevel);
1.539     albertel 7659: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7660: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7661: 
1.218     albertel 7662: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7663: 
1.60      www      7664: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7665: 	    my $symbp=$symbparm;
1.735     albertel 7666: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7667: 
                   7668: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7669: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7670: 
1.620     albertel 7671: 	    if (($env{'user.name'} eq $uname) &&
                   7672: 		($env{'user.domain'} eq $udom)) {
                   7673: 		$section=$env{'request.course.sec'};
1.733     raeburn  7674:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7675:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7676: 	    } else {
1.539     albertel 7677: 		if (! defined($usection)) {
1.551     albertel 7678: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7679: 		} else {
                   7680: 		    $section = $usection;
                   7681: 		}
1.733     raeburn  7682:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7683: 	    }
                   7684: 
                   7685: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7686: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7687: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7688: 
1.593     albertel 7689: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7690: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7691: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7692: 
1.60      www      7693: # ----------------------------------------------------------- first, check user
1.624     albertel 7694: 
                   7695: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7696: 				       ([$courselevelr,'resource'],
                   7697: 					[$courselevelm,'map'     ],
                   7698: 					[$courselevel, 'course'  ]));
1.931     albertel 7699: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7700: 
1.594     albertel 7701: # ------------------------------------------------ second, check some of course
1.684     raeburn  7702:             my $coursereply;
1.691     raeburn  7703:             if (@groups > 0) {
                   7704:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7705:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7706:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7707:             }
1.96      www      7708: 
1.684     raeburn  7709: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7710: 				  $env{'course.'.$courseid.'.domain'},
                   7711: 				  'course',
                   7712: 				  ([$seclevelr,   'resource'],
                   7713: 				   [$seclevelm,   'map'     ],
                   7714: 				   [$seclevel,    'course'  ],
                   7715: 				   [$courselevelr,'resource']));
                   7716: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7717: 
1.60      www      7718: # ------------------------------------------------------ third, check map parms
1.218     albertel 7719: 	    my %parmhash=();
                   7720: 	    my $thisparm='';
                   7721: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7722: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7723: 		    &GDBM_READER(),0640)) {
1.218     albertel 7724: 		$thisparm=$parmhash{$symbparm};
                   7725: 		untie(%parmhash);
                   7726: 	    }
1.927     albertel 7727: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7728: 	}
1.594     albertel 7729: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7730: 
1.218     albertel 7731: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7732: 	my $filename;
                   7733: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7734: 	if ($symbparm) {
1.409     www      7735: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7736: 	} else {
1.620     albertel 7737: 	    $filename=$env{'request.filename'};
1.282     albertel 7738: 	}
                   7739: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7740: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7741: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7742: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7743: 
1.927     albertel 7744: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7745: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7746: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7747: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7748: 				     $env{'course.'.$courseid.'.domain'},
                   7749: 				     'course',
1.927     albertel 7750: 				     ([$courselevelm,'map'   ],
                   7751: 				      [$courselevel, 'course']));
                   7752: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7753: 	}
1.145     www      7754: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7755: 	unless ($space eq '0') {
1.336     albertel 7756: 	    my @parts=split(/_/,$space);
                   7757: 	    my $id=pop(@parts);
                   7758: 	    my $part=join('_',@parts);
                   7759: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7760: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7761: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7762: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7763: 	}
1.395     albertel 7764: 	if ($recurse) { return undef; }
                   7765: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7766: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7767: # ---------------------------------------------------- Any other user namespace
                   7768:     } elsif ($realm eq 'environment') {
                   7769: # ----------------------------------------------------------------- environment
1.620     albertel 7770: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7771: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7772: 	} else {
1.770     albertel 7773: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7774: 		return '';
                   7775: 	    }
1.219     albertel 7776: 	    my %returnhash=&userenvironment($udom,$uname,
                   7777: 					    $spacequalifierrest);
                   7778: 	    return $returnhash{$spacequalifierrest};
                   7779: 	}
1.28      www      7780:     } elsif ($realm eq 'system') {
1.48      www      7781: # ----------------------------------------------------------------- system.time
                   7782: 	if ($space eq 'time') {
                   7783: 	    return time;
                   7784:         }
1.696     albertel 7785:     } elsif ($realm eq 'server') {
                   7786: # ----------------------------------------------------------------- system.time
                   7787: 	if ($space eq 'name') {
                   7788: 	    return $ENV{'SERVER_NAME'};
                   7789:         }
1.28      www      7790:     }
1.48      www      7791:     return '';
1.61      www      7792: }
                   7793: 
1.927     albertel 7794: sub get_reply {
                   7795:     my ($reply_value) = @_;
1.940     raeburn  7796:     if (ref($reply_value) eq 'ARRAY') {
                   7797:         if (wantarray) {
                   7798: 	    return @$reply_value;
                   7799:         }
                   7800:         return $reply_value->[0];
                   7801:     } else {
                   7802:         return $reply_value;
1.927     albertel 7803:     }
                   7804: }
                   7805: 
1.691     raeburn  7806: sub check_group_parms {
                   7807:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7808:     my @groupitems = ();
                   7809:     my $resultitem;
1.927     albertel 7810:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7811:     foreach my $group (@{$groups}) {
                   7812:         foreach my $level (@levels) {
1.927     albertel 7813:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7814:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7815:         }
                   7816:     }
                   7817:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7818:                             $env{'course.'.$courseid.'.domain'},
                   7819:                                      'course',@groupitems);
                   7820:     return $coursereply;
                   7821: }
                   7822: 
                   7823: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7824:     my ($courseid,@groups) = @_;
                   7825:     @groups = sort(@groups);
1.691     raeburn  7826:     return @groups;
                   7827: }
                   7828: 
1.395     albertel 7829: sub packages_tab_default {
                   7830:     my ($uri,$varname)=@_;
                   7831:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7832: 
                   7833:     my (@extension,@specifics,$do_default);
                   7834:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7835: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7836: 	if ($pack_type eq 'default') {
                   7837: 	    $do_default=1;
                   7838: 	} elsif ($pack_type eq 'extension') {
                   7839: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7840: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7841: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7842: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7843: 	}
                   7844:     }
                   7845:     # first look for a package that matches the requested part id
                   7846:     foreach my $package (@specifics) {
                   7847: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7848: 	next if ($pack_part ne $part);
                   7849: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7850: 	    return $packagetab{"$pack_type&$name&default"};
                   7851: 	}
                   7852:     }
                   7853:     # look for any possible matching non extension_ package
                   7854:     foreach my $package (@specifics) {
                   7855: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7856: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7857: 	    return $packagetab{"$pack_type&$name&default"};
                   7858: 	}
1.585     albertel 7859: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7860: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7861: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7862: 	}
                   7863:     }
1.738     albertel 7864:     # look for any posible extension_ match
                   7865:     foreach my $package (@extension) {
                   7866: 	my ($package,$pack_type)=@{$package};
                   7867: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7868: 	    return $packagetab{"$pack_type&$name&default"};
                   7869: 	}
                   7870: 	if (defined($packagetab{$package."&$name&default"})) {
                   7871: 	    return $packagetab{$package."&$name&default"};
                   7872: 	}
                   7873:     }
                   7874:     # look for a global default setting
                   7875:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7876: 	return $packagetab{"default&$name&default"};
                   7877:     }
1.395     albertel 7878:     return undef;
                   7879: }
                   7880: 
1.334     albertel 7881: sub add_prefix_and_part {
                   7882:     my ($prefix,$part)=@_;
                   7883:     my $keyroot;
                   7884:     if (defined($prefix) && $prefix !~ /^__/) {
                   7885: 	# prefix that has a part already
                   7886: 	$keyroot=$prefix;
                   7887:     } elsif (defined($prefix)) {
                   7888: 	# prefix that is missing a part
                   7889: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7890:     } else {
                   7891: 	# no prefix at all
                   7892: 	if (defined($part)) { $keyroot='_'.$part; }
                   7893:     }
                   7894:     return $keyroot;
                   7895: }
                   7896: 
1.71      www      7897: # ---------------------------------------------------------------- Get metadata
                   7898: 
1.599     albertel 7899: my %metaentry;
1.71      www      7900: sub metadata {
1.176     www      7901:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7902:     $uri=&declutter($uri);
1.288     albertel 7903:     # if it is a non metadata possible uri return quickly
1.529     albertel 7904:     if (($uri eq '') || 
                   7905: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7906: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7907:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7908: 	return undef;
                   7909:     }
                   7910:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7911: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7912: 	return undef;
1.288     albertel 7913:     }
1.73      www      7914:     my $filename=$uri;
                   7915:     $uri=~s/\.meta$//;
1.172     www      7916: #
                   7917: # Is the metadata already cached?
1.177     www      7918: # Look at timestamp of caching
1.172     www      7919: # Everything is cached by the main uri, libraries are never directly cached
                   7920: #
1.428     albertel 7921:     if (!defined($liburi)) {
1.599     albertel 7922: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7923: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7924:     }
                   7925:     {
1.172     www      7926: #
                   7927: # Is this a recursive call for a library?
                   7928: #
1.599     albertel 7929: #	if (! exists($metacache{$uri})) {
                   7930: #	    $metacache{$uri}={};
                   7931: #	}
1.924     albertel 7932: 	my $cachetime = 60*60;
1.171     www      7933:         if ($liburi) {
                   7934: 	    $liburi=&declutter($liburi);
                   7935:             $filename=$liburi;
1.401     bowersj2 7936:         } else {
1.599     albertel 7937: 	    &devalidate_cache_new('meta',$uri);
                   7938: 	    undef(%metaentry);
1.401     bowersj2 7939: 	}
1.140     www      7940:         my %metathesekeys=();
1.73      www      7941:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7942: 	my $metastring;
1.924     albertel 7943: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7944: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7945: 	    $metastring = 
1.929     albertel 7946: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7947: 					  ('grade_target' => 'meta'));
                   7948: 	    $cachetime = 1; # only want this cached in the child not long term
                   7949: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7950: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7951: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7952: 	    $metastring=&getfile($file);
1.489     albertel 7953: 	}
1.208     albertel 7954:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7955:         my $token;
1.140     www      7956:         undef %metathesekeys;
1.71      www      7957:         while ($token=$parser->get_token) {
1.339     albertel 7958: 	    if ($token->[0] eq 'S') {
                   7959: 		if (defined($token->[2]->{'package'})) {
1.172     www      7960: #
                   7961: # This is a package - get package info
                   7962: #
1.339     albertel 7963: 		    my $package=$token->[2]->{'package'};
                   7964: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7965: 		    if (defined($token->[2]->{'id'})) { 
                   7966: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7967: 		    }
1.599     albertel 7968: 		    if ($metaentry{':packages'}) {
                   7969: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7970: 		    } else {
1.599     albertel 7971: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7972: 		    }
1.736     albertel 7973: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7974: 			my $part=$keyroot;
                   7975: 			$part=~s/^\_//;
1.736     albertel 7976: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7977: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7978: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7979: 			    # ignore package.tab specified default values
                   7980:                             # here &package_tab_default() will fetch those
                   7981: 			    if ($subp eq 'default') { next; }
1.736     albertel 7982: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7983: 			    my $unikey;
                   7984: 			    if ($pack =~ /_0$/) {
                   7985: 				$unikey='parameter_0_'.$name;
                   7986: 				$part=0;
                   7987: 			    } else {
                   7988: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7989: 			    }
1.339     albertel 7990: 			    if ($subp eq 'display') {
                   7991: 				$value.=' [Part: '.$part.']';
                   7992: 			    }
1.599     albertel 7993: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7994: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7995: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7996: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7997: 			    }
1.599     albertel 7998: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7999: 				$metaentry{':'.$unikey}=
                   8000: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8001: 			    }
1.339     albertel 8002: 			}
                   8003: 		    }
                   8004: 		} else {
1.172     www      8005: #
                   8006: # This is not a package - some other kind of start tag
1.339     albertel 8007: #
                   8008: 		    my $entry=$token->[1];
                   8009: 		    my $unikey;
                   8010: 		    if ($entry eq 'import') {
                   8011: 			$unikey='';
                   8012: 		    } else {
                   8013: 			$unikey=$entry;
                   8014: 		    }
                   8015: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8016: 
                   8017: 		    if (defined($token->[2]->{'id'})) { 
                   8018: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8019: 		    }
1.175     www      8020: 
1.339     albertel 8021: 		    if ($entry eq 'import') {
1.175     www      8022: #
                   8023: # Importing a library here
1.339     albertel 8024: #
                   8025: 			if ($depthcount<20) {
                   8026: 			    my $location=$parser->get_text('/import');
                   8027: 			    my $dir=$filename;
                   8028: 			    $dir=~s|[^/]*$||;
                   8029: 			    $location=&filelocation($dir,$location);
1.736     albertel 8030: 			    my $metadata = 
                   8031: 				&metadata($uri,'keys', $location,$unikey,
                   8032: 					  $depthcount+1);
                   8033: 			    foreach my $meta (split(',',$metadata)) {
                   8034: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8035: 				$metathesekeys{$meta}=1;
1.339     albertel 8036: 			    }
                   8037: 			}
                   8038: 		    } else { 
                   8039: 			
                   8040: 			if (defined($token->[2]->{'name'})) { 
                   8041: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8042: 			}
                   8043: 			$metathesekeys{$unikey}=1;
1.736     albertel 8044: 			foreach my $param (@{$token->[3]}) {
                   8045: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8046: 				$token->[2]->{$param};
1.339     albertel 8047: 			}
                   8048: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8049: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8050: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8051: 		 # only ws inside the tag, and not in default, so use default
                   8052: 		 # as value
1.599     albertel 8053: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8054: 			} elsif ( $internaltext =~ /\S/ ) {
                   8055: 		  # something interesting inside the tag
                   8056: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8057: 			} else {
1.908     albertel 8058: 		  # no interesting values, don't set a default
1.339     albertel 8059: 			}
1.172     www      8060: # end of not-a-package not-a-library import
1.339     albertel 8061: 		    }
1.172     www      8062: # end of not-a-package start tag
1.339     albertel 8063: 		}
1.172     www      8064: # the next is the end of "start tag"
1.339     albertel 8065: 	    }
                   8066: 	}
1.483     albertel 8067: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8068: 	$extension = lc($extension);
                   8069: 	if ($extension eq 'htm') { $extension='html'; }
                   8070: 
1.737     albertel 8071: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8072: 	    #no specific packages #how's our extension
                   8073: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8074: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8075: 					 \%metathesekeys);
                   8076: 	}
1.883     albertel 8077: 
                   8078: 	if (!exists($metaentry{':packages'})
                   8079: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8080: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8081: 		#no specific packages well let's get default then
                   8082: 		if ($key!~/^default&/) { next; }
1.488     albertel 8083: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8084: 					     \%metathesekeys);
                   8085: 	    }
                   8086: 	}
1.338     www      8087: # are there custom rights to evaluate
1.599     albertel 8088: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8089: 
1.338     www      8090:     #
                   8091:     # Importing a rights file here
1.339     albertel 8092:     #
                   8093: 	    unless ($depthcount) {
1.599     albertel 8094: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8095: 		my $dir=$filename;
                   8096: 		$dir=~s|[^/]*$||;
                   8097: 		$location=&filelocation($dir,$location);
1.736     albertel 8098: 		my $rights_metadata =
                   8099: 		    &metadata($uri,'keys',$location,'_rights',
                   8100: 			      $depthcount+1);
                   8101: 		foreach my $rights (split(',',$rights_metadata)) {
                   8102: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8103: 		    $metathesekeys{$rights}=1;
1.339     albertel 8104: 		}
                   8105: 	    }
                   8106: 	}
1.737     albertel 8107: 	# uniqifiy package listing
                   8108: 	my %seen;
                   8109: 	my @uniq_packages =
                   8110: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8111: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8112: 
                   8113: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8114: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8115: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8116: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8117: # this is the end of "was not already recently cached
1.71      www      8118:     }
1.599     albertel 8119:     return $metaentry{':'.$what};
1.261     albertel 8120: }
                   8121: 
1.488     albertel 8122: sub metadata_create_package_def {
1.483     albertel 8123:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8124:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8125:     if ($subp eq 'default') { next; }
                   8126:     
1.599     albertel 8127:     if (defined($metaentry{':packages'})) {
                   8128: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8129:     } else {
1.599     albertel 8130: 	$metaentry{':packages'}=$package;
1.483     albertel 8131:     }
                   8132:     my $value=$packagetab{$key};
                   8133:     my $unikey;
                   8134:     $unikey='parameter_0_'.$name;
1.599     albertel 8135:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8136:     $$metathesekeys{$unikey}=1;
1.599     albertel 8137:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8138: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8139:     }
1.599     albertel 8140:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8141: 	$metaentry{':'.$unikey}=
                   8142: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8143:     }
                   8144: }
                   8145: 
1.261     albertel 8146: sub metadata_generate_part0 {
                   8147:     my ($metadata,$metacache,$uri) = @_;
                   8148:     my %allnames;
1.737     albertel 8149:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8150: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8151: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8152: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8153: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8154: 	    $allnames{$name}=$part;
                   8155: 	  }
                   8156: 	}
                   8157:     }
                   8158:     foreach my $name (keys(%allnames)) {
                   8159:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8160:       my $key=":parameter_0_$name";
1.261     albertel 8161:       $$metacache{"$key.part"}='0';
                   8162:       $$metacache{"$key.name"}=$name;
1.428     albertel 8163:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8164: 					   $allnames{$name}.'_'.$name.
                   8165: 					   '.type'};
1.428     albertel 8166:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8167: 			     '.display'};
1.644     www      8168:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8169:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8170:       $$metacache{"$key.display"}=$olddis;
                   8171:     }
1.71      www      8172: }
                   8173: 
1.764     albertel 8174: # ------------------------------------------------------ Devalidate title cache
                   8175: 
                   8176: sub devalidate_title_cache {
                   8177:     my ($url)=@_;
                   8178:     if (!$env{'request.course.id'}) { return; }
                   8179:     my $symb=&symbread($url);
                   8180:     if (!$symb) { return; }
                   8181:     my $key=$env{'request.course.id'}."\0".$symb;
                   8182:     &devalidate_cache_new('title',$key);
                   8183: }
                   8184: 
1.1014    droeschl 8185: # ------------------------------------------------- Get the title of a course
                   8186: 
                   8187: sub current_course_title {
                   8188:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8189: }
1.301     www      8190: # ------------------------------------------------- Get the title of a resource
                   8191: 
                   8192: sub gettitle {
                   8193:     my $urlsymb=shift;
                   8194:     my $symb=&symbread($urlsymb);
1.534     albertel 8195:     if ($symb) {
1.620     albertel 8196: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8197: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8198: 	if (defined($cached)) { 
                   8199: 	    return $result;
                   8200: 	}
1.534     albertel 8201: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8202: 	my $title='';
1.907     albertel 8203: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8204: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8205: 	} else {
                   8206: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8207: 		    &GDBM_READER(),0640)) {
                   8208: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8209: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8210: 		untie(%bighash);
                   8211: 	    }
1.534     albertel 8212: 	}
                   8213: 	$title=~s/\&colon\;/\:/gs;
                   8214: 	if ($title) {
1.599     albertel 8215: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8216: 	}
                   8217: 	$urlsymb=$url;
                   8218:     }
                   8219:     my $title=&metadata($urlsymb,'title');
                   8220:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8221:     return $title;
1.301     www      8222: }
1.613     albertel 8223: 
1.614     albertel 8224: sub get_slot {
                   8225:     my ($which,$cnum,$cdom)=@_;
                   8226:     if (!$cnum || !$cdom) {
1.790     albertel 8227: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8228: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8229: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8230:     }
1.703     albertel 8231:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8232:     my %slotinfo;
                   8233:     if (exists($remembered{$key})) {
                   8234: 	$slotinfo{$which} = $remembered{$key};
                   8235:     } else {
                   8236: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8237: 	&Apache::lonhomework::showhash(%slotinfo);
                   8238: 	my ($tmp)=keys(%slotinfo);
                   8239: 	if ($tmp=~/^error:/) { return (); }
                   8240: 	$remembered{$key} = $slotinfo{$which};
                   8241:     }
1.616     albertel 8242:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8243: 	return %{$slotinfo{$which}};
                   8244:     }
                   8245:     return $slotinfo{$which};
1.614     albertel 8246: }
1.31      www      8247: # ------------------------------------------------- Update symbolic store links
                   8248: 
                   8249: sub symblist {
                   8250:     my ($mapname,%newhash)=@_;
1.438     www      8251:     $mapname=&deversion(&declutter($mapname));
1.31      www      8252:     my %hash;
1.620     albertel 8253:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8254:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8255:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8256: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8257: 		next if ($url eq 'last_known'
                   8258: 			 && $env{'form.no_update_last_known'});
                   8259: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8260: 						    $newhash{$url}->[1],
                   8261: 						    $newhash{$url}->[0]);
1.191     harris41 8262:             }
1.31      www      8263:             if (untie(%hash)) {
                   8264: 		return 'ok';
                   8265:             }
                   8266:         }
                   8267:     }
                   8268:     return 'error';
1.212     www      8269: }
                   8270: 
                   8271: # --------------------------------------------------------------- Verify a symb
                   8272: 
                   8273: sub symbverify {
1.510     www      8274:     my ($symb,$thisurl)=@_;
                   8275:     my $thisfn=$thisurl;
1.439     www      8276:     $thisfn=&declutter($thisfn);
1.215     www      8277: # direct jump to resource in page or to a sequence - will construct own symbs
                   8278:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8279: # check URL part
1.409     www      8280:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8281: 
1.431     www      8282:     unless ($url eq $thisfn) { return 0; }
1.213     www      8283: 
1.216     www      8284:     $symb=&symbclean($symb);
1.510     www      8285:     $thisurl=&deversion($thisurl);
1.439     www      8286:     $thisfn=&deversion($thisfn);
1.213     www      8287: 
                   8288:     my %bighash;
                   8289:     my $okay=0;
1.431     www      8290: 
1.620     albertel 8291:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8292:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8293:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8294:             $thisurl =~ s/\?.+$//;
                   8295:         }
1.510     www      8296:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8297:         unless ($ids) { 
1.510     www      8298:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8299:         }
                   8300:         if ($ids) {
                   8301: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8302: 	    foreach my $id (split(/\,/,$ids)) {
                   8303: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8304:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8305:                    $symb =~ s/\?.+$//;
                   8306:                }
1.216     www      8307:                if (
                   8308:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8309:    eq $symb) { 
1.620     albertel 8310: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8311: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8312: 		       $okay=1; 
                   8313: 		   }
                   8314: 	       }
1.216     www      8315: 	   }
                   8316:         }
1.213     www      8317: 	untie(%bighash);
                   8318:     }
                   8319:     return $okay;
1.31      www      8320: }
                   8321: 
1.210     www      8322: # --------------------------------------------------------------- Clean-up symb
                   8323: 
                   8324: sub symbclean {
                   8325:     my $symb=shift;
1.568     albertel 8326:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8327: # remove version from map
                   8328:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8329: 
1.210     www      8330: # remove version from URL
                   8331:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8332: 
1.507     www      8333: # remove wrapper
                   8334: 
1.510     www      8335:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8336:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8337:     return $symb;
1.409     www      8338: }
                   8339: 
                   8340: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8341: 
                   8342: sub encode_symb {
                   8343:     my ($map,$resid,$url)=@_;
                   8344:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8345: }
1.409     www      8346: 
                   8347: sub decode_symb {
1.568     albertel 8348:     my $symb=shift;
                   8349:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8350:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8351:     return (&fixversion($map),$resid,&fixversion($url));
                   8352: }
                   8353: 
                   8354: sub fixversion {
                   8355:     my $fn=shift;
1.609     banghart 8356:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8357:     my %bighash;
                   8358:     my $uri=&clutter($fn);
1.620     albertel 8359:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8360: # is this cached?
1.599     albertel 8361:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8362:     if (defined($cached)) { return $result; }
                   8363: # unfortunately not cached, or expired
1.620     albertel 8364:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8365: 	    &GDBM_READER(),0640)) {
                   8366:  	if ($bighash{'version_'.$uri}) {
                   8367:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8368:  	    unless (($version eq 'mostrecent') || 
                   8369: 		    ($version==&getversion($uri))) {
1.440     www      8370:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8371:  	    }
                   8372:  	}
                   8373:  	untie %bighash;
1.413     www      8374:     }
1.599     albertel 8375:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8376: }
                   8377: 
                   8378: sub deversion {
                   8379:     my $url=shift;
                   8380:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8381:     return $url;
1.210     www      8382: }
                   8383: 
1.31      www      8384: # ------------------------------------------------------ Return symb list entry
                   8385: 
                   8386: sub symbread {
1.249     www      8387:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8388:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8389:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8390: # no filename provided? try from environment
1.44      www      8391:     unless ($thisfn) {
1.620     albertel 8392:         if ($env{'request.symb'}) {
                   8393: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8394: 	}
1.620     albertel 8395: 	$thisfn=$env{'request.filename'};
1.44      www      8396:     }
1.569     albertel 8397:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8398: # is that filename actually a symb? Verify, clean, and return
                   8399:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8400: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8401: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8402: 	}
1.242     www      8403:     }
1.44      www      8404:     $thisfn=declutter($thisfn);
1.31      www      8405:     my %hash;
1.37      www      8406:     my %bighash;
                   8407:     my $syval='';
1.620     albertel 8408:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8409:         my $targetfn = $thisfn;
1.609     banghart 8410:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8411:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8412:         }
1.687     albertel 8413: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8414: 	    $targetfn=$1;
                   8415: 	}
1.620     albertel 8416:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8417:                       &GDBM_READER(),0640)) {
1.481     raeburn  8418: 	    $syval=$hash{$targetfn};
1.37      www      8419:             untie(%hash);
                   8420:         }
                   8421: # ---------------------------------------------------------- There was an entry
                   8422:         if ($syval) {
1.601     albertel 8423: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8424: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8425: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8426: 		    #return $env{$cache_str}='';
1.601     albertel 8427: 		#}    
                   8428: 		#$syval.=$1;
                   8429: 	    #}
1.37      www      8430:         } else {
                   8431: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8432:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8433:                             &GDBM_READER(),0640)) {
1.37      www      8434: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8435:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8436:               unless ($ids) { 
                   8437:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8438:               }
                   8439:               unless ($ids) {
                   8440: # alias?
                   8441: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8442:               }
1.37      www      8443:               if ($ids) {
                   8444: # ------------------------------------------------------------------- Has ID(s)
                   8445:                  my @possibilities=split(/\,/,$ids);
1.39      www      8446:                  if ($#possibilities==0) {
                   8447: # ----------------------------------------------- There is only one possibility
1.37      www      8448: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8449: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8450: 						    $resid,$thisfn);
1.249     www      8451:                  } elsif (!$donotrecurse) {
1.39      www      8452: # ------------------------------------------ There is more than one possibility
                   8453:                      my $realpossible=0;
1.800     albertel 8454:                      foreach my $id (@possibilities) {
                   8455: 			 my $file=$bighash{'src_'.$id};
1.39      www      8456:                          if (&allowed('bre',$file)) {
1.800     albertel 8457:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8458:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8459: 				$realpossible++;
1.626     albertel 8460:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8461: 						    $resid,$thisfn);
1.39      www      8462:                             }
                   8463: 			 }
1.191     harris41 8464:                      }
1.39      www      8465: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8466:                  } else {
                   8467:                      $syval='';
1.37      www      8468:                  }
                   8469: 	      }
                   8470:               untie(%bighash)
1.481     raeburn  8471:            }
1.31      www      8472:         }
1.62      www      8473:         if ($syval) {
1.620     albertel 8474: 	    return $env{$cache_str}=$syval;
1.62      www      8475:         }
1.31      www      8476:     }
1.949     raeburn  8477:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8478:     return $env{$cache_str}='';
1.31      www      8479: }
                   8480: 
                   8481: # ---------------------------------------------------------- Return random seed
                   8482: 
1.32      www      8483: sub numval {
                   8484:     my $txt=shift;
                   8485:     $txt=~tr/A-J/0-9/;
                   8486:     $txt=~tr/a-j/0-9/;
                   8487:     $txt=~tr/K-T/0-9/;
                   8488:     $txt=~tr/k-t/0-9/;
                   8489:     $txt=~tr/U-Z/0-5/;
                   8490:     $txt=~tr/u-z/0-5/;
                   8491:     $txt=~s/\D//g;
1.564     albertel 8492:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8493:     return int($txt);
1.368     albertel 8494: }
                   8495: 
1.484     albertel 8496: sub numval2 {
                   8497:     my $txt=shift;
                   8498:     $txt=~tr/A-J/0-9/;
                   8499:     $txt=~tr/a-j/0-9/;
                   8500:     $txt=~tr/K-T/0-9/;
                   8501:     $txt=~tr/k-t/0-9/;
                   8502:     $txt=~tr/U-Z/0-5/;
                   8503:     $txt=~tr/u-z/0-5/;
                   8504:     $txt=~s/\D//g;
                   8505:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8506:     my $total;
                   8507:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8508:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8509:     return int($total);
                   8510: }
                   8511: 
1.575     albertel 8512: sub numval3 {
                   8513:     use integer;
                   8514:     my $txt=shift;
                   8515:     $txt=~tr/A-J/0-9/;
                   8516:     $txt=~tr/a-j/0-9/;
                   8517:     $txt=~tr/K-T/0-9/;
                   8518:     $txt=~tr/k-t/0-9/;
                   8519:     $txt=~tr/U-Z/0-5/;
                   8520:     $txt=~tr/u-z/0-5/;
                   8521:     $txt=~s/\D//g;
                   8522:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8523:     my $total;
                   8524:     foreach my $val (@txts) { $total+=$val; }
                   8525:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8526:     return $total;
                   8527: }
                   8528: 
1.675     albertel 8529: sub digest {
                   8530:     my ($data)=@_;
                   8531:     my $digest=&Digest::MD5::md5($data);
                   8532:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8533:     my ($e,$f);
                   8534:     {
                   8535:         use integer;
                   8536:         $e=($a+$b);
                   8537:         $f=($c+$d);
                   8538:         if ($_64bit) {
                   8539:             $e=(($e<<32)>>32);
                   8540:             $f=(($f<<32)>>32);
                   8541:         }
                   8542:     }
                   8543:     if (wantarray) {
                   8544: 	return ($e,$f);
                   8545:     } else {
                   8546: 	my $g;
                   8547: 	{
                   8548: 	    use integer;
                   8549: 	    $g=($e+$f);
                   8550: 	    if ($_64bit) {
                   8551: 		$g=(($g<<32)>>32);
                   8552: 	    }
                   8553: 	}
                   8554: 	return $g;
                   8555:     }
                   8556: }
                   8557: 
1.368     albertel 8558: sub latest_rnd_algorithm_id {
1.675     albertel 8559:     return '64bit5';
1.366     albertel 8560: }
1.32      www      8561: 
1.503     albertel 8562: sub get_rand_alg {
                   8563:     my ($courseid)=@_;
1.790     albertel 8564:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8565:     if ($courseid) {
1.620     albertel 8566: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8567:     }
                   8568:     return &latest_rnd_algorithm_id();
                   8569: }
                   8570: 
1.562     albertel 8571: sub validCODE {
                   8572:     my ($CODE)=@_;
                   8573:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8574:     return 0;
                   8575: }
                   8576: 
1.491     albertel 8577: sub getCODE {
1.620     albertel 8578:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8579:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8580: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8581: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8582: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8583:     }
                   8584:     return undef;
                   8585: }
                   8586: 
1.31      www      8587: sub rndseed {
1.155     albertel 8588:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8589:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8590:     if (!defined($symb)) {
1.366     albertel 8591: 	unless ($symb=$wsymb) { return time; }
                   8592:     }
                   8593:     if (!$courseid) { $courseid=$wcourseid; }
                   8594:     if (!$domain) { $domain=$wdomain; }
                   8595:     if (!$username) { $username=$wusername }
1.503     albertel 8596:     my $which=&get_rand_alg();
1.803     albertel 8597: 
1.491     albertel 8598:     if (defined(&getCODE())) {
1.675     albertel 8599: 	if ($which eq '64bit5') {
                   8600: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8601: 	} elsif ($which eq '64bit4') {
1.575     albertel 8602: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8603: 	} else {
                   8604: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8605: 	}
1.675     albertel 8606:     } elsif ($which eq '64bit5') {
                   8607: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8608:     } elsif ($which eq '64bit4') {
                   8609: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8610:     } elsif ($which eq '64bit3') {
                   8611: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8612:     } elsif ($which eq '64bit2') {
                   8613: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8614:     } elsif ($which eq '64bit') {
                   8615: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8616:     }
                   8617:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8618: }
                   8619: 
                   8620: sub rndseed_32bit {
                   8621:     my ($symb,$courseid,$domain,$username)=@_;
                   8622:     {
                   8623: 	use integer;
                   8624: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8625: 	my $symbseed=numval($symb) << 22;
                   8626: 	my $namechck=unpack("%32C*",$username) << 17;
                   8627: 	my $nameseed=numval($username) << 12;
                   8628: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8629: 	my $courseseed=unpack("%32C*",$courseid);
                   8630: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8631: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8632: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8633: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8634: 	return $num;
                   8635:     }
                   8636: }
                   8637: 
                   8638: sub rndseed_64bit {
                   8639:     my ($symb,$courseid,$domain,$username)=@_;
                   8640:     {
                   8641: 	use integer;
                   8642: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8643: 	my $symbseed=numval($symb) << 10;
                   8644: 	my $namechck=unpack("%32S*",$username);
                   8645: 	
                   8646: 	my $nameseed=numval($username) << 21;
                   8647: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8648: 	my $courseseed=unpack("%32S*",$courseid);
                   8649: 	
                   8650: 	my $num1=$symbchck+$symbseed+$namechck;
                   8651: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8652: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8653: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8654: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8655: 	return "$num1,$num2";
1.155     albertel 8656:     }
1.366     albertel 8657: }
                   8658: 
1.443     albertel 8659: sub rndseed_64bit2 {
                   8660:     my ($symb,$courseid,$domain,$username)=@_;
                   8661:     {
                   8662: 	use integer;
                   8663: 	# strings need to be an even # of cahracters long, it it is odd the
                   8664:         # last characters gets thrown away
                   8665: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8666: 	my $symbseed=numval($symb) << 10;
                   8667: 	my $namechck=unpack("%32S*",$username.' ');
                   8668: 	
                   8669: 	my $nameseed=numval($username) << 21;
1.501     albertel 8670: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8671: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8672: 	
                   8673: 	my $num1=$symbchck+$symbseed+$namechck;
                   8674: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8675: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8676: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8677: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8678: 	return "$num1,$num2";
                   8679:     }
                   8680: }
                   8681: 
                   8682: sub rndseed_64bit3 {
                   8683:     my ($symb,$courseid,$domain,$username)=@_;
                   8684:     {
                   8685: 	use integer;
                   8686: 	# strings need to be an even # of cahracters long, it it is odd the
                   8687:         # last characters gets thrown away
                   8688: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8689: 	my $symbseed=numval2($symb) << 10;
                   8690: 	my $namechck=unpack("%32S*",$username.' ');
                   8691: 	
                   8692: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8693: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8694: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8695: 	
                   8696: 	my $num1=$symbchck+$symbseed+$namechck;
                   8697: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8698: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8699: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8700: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8701: 	
1.503     albertel 8702: 	return "$num1:$num2";
1.443     albertel 8703:     }
                   8704: }
                   8705: 
1.575     albertel 8706: sub rndseed_64bit4 {
                   8707:     my ($symb,$courseid,$domain,$username)=@_;
                   8708:     {
                   8709: 	use integer;
                   8710: 	# strings need to be an even # of cahracters long, it it is odd the
                   8711:         # last characters gets thrown away
                   8712: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8713: 	my $symbseed=numval3($symb) << 10;
                   8714: 	my $namechck=unpack("%32S*",$username.' ');
                   8715: 	
                   8716: 	my $nameseed=numval3($username) << 21;
                   8717: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8718: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8719: 	
                   8720: 	my $num1=$symbchck+$symbseed+$namechck;
                   8721: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8722: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8723: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8724: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8725: 	
                   8726: 	return "$num1:$num2";
                   8727:     }
                   8728: }
                   8729: 
1.675     albertel 8730: sub rndseed_64bit5 {
                   8731:     my ($symb,$courseid,$domain,$username)=@_;
                   8732:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8733:     return "$num1:$num2";
                   8734: }
                   8735: 
1.366     albertel 8736: sub rndseed_CODE_64bit {
                   8737:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8738:     {
1.366     albertel 8739: 	use integer;
1.443     albertel 8740: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8741: 	my $symbseed=numval2($symb);
1.491     albertel 8742: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8743: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8744: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8745: 	my $num1=$symbseed+$CODEchck;
                   8746: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8747: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8748: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8749: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8750: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8751: 	return "$num1:$num2";
1.366     albertel 8752:     }
                   8753: }
                   8754: 
1.575     albertel 8755: sub rndseed_CODE_64bit4 {
                   8756:     my ($symb,$courseid,$domain,$username)=@_;
                   8757:     {
                   8758: 	use integer;
                   8759: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8760: 	my $symbseed=numval3($symb);
                   8761: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8762: 	my $CODEseed=numval3(&getCODE());
                   8763: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8764: 	my $num1=$symbseed+$CODEchck;
                   8765: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8766: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8767: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8768: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8769: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8770: 	return "$num1:$num2";
                   8771:     }
                   8772: }
                   8773: 
1.675     albertel 8774: sub rndseed_CODE_64bit5 {
                   8775:     my ($symb,$courseid,$domain,$username)=@_;
                   8776:     my $code = &getCODE();
                   8777:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8778:     return "$num1:$num2";
                   8779: }
                   8780: 
1.366     albertel 8781: sub setup_random_from_rndseed {
                   8782:     my ($rndseed)=@_;
1.503     albertel 8783:     if ($rndseed =~/([,:])/) {
                   8784: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8785: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8786:     } else {
                   8787: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8788:     }
1.36      albertel 8789: }
                   8790: 
1.474     albertel 8791: sub latest_receipt_algorithm_id {
1.835     albertel 8792:     return 'receipt3';
1.474     albertel 8793: }
                   8794: 
1.480     www      8795: sub recunique {
                   8796:     my $fucourseid=shift;
                   8797:     my $unique;
1.835     albertel 8798:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8799: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8800: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8801:     } else {
                   8802: 	$unique=$perlvar{'lonReceipt'};
                   8803:     }
                   8804:     return unpack("%32C*",$unique);
                   8805: }
                   8806: 
                   8807: sub recprefix {
                   8808:     my $fucourseid=shift;
                   8809:     my $prefix;
1.835     albertel 8810:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8811: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8812: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8813:     } else {
                   8814: 	$prefix=$perlvar{'lonHostID'};
                   8815:     }
                   8816:     return unpack("%32C*",$prefix);
                   8817: }
                   8818: 
1.76      www      8819: sub ireceipt {
1.474     albertel 8820:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8821: 
                   8822:     my $return =&recprefix($fucourseid).'-';
                   8823: 
                   8824:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8825: 	$env{'request.state'} eq 'construct') {
                   8826: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8827: 	return $return;
                   8828:     }
                   8829: 
1.76      www      8830:     my $cuname=unpack("%32C*",$funame);
                   8831:     my $cudom=unpack("%32C*",$fudom);
                   8832:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8833:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8834:     my $cunique=&recunique($fucourseid);
1.474     albertel 8835:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8836:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8837: 
1.790     albertel 8838: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8839: 			       
                   8840: 	$return.= ($cunique%$cuname+
                   8841: 		   $cunique%$cudom+
                   8842: 		   $cusymb%$cuname+
                   8843: 		   $cusymb%$cudom+
                   8844: 		   $cucourseid%$cuname+
                   8845: 		   $cucourseid%$cudom+
                   8846: 		   $cpart%$cuname+
                   8847: 		   $cpart%$cudom);
                   8848:     } else {
                   8849: 	$return.= ($cunique%$cuname+
                   8850: 		   $cunique%$cudom+
                   8851: 		   $cusymb%$cuname+
                   8852: 		   $cusymb%$cudom+
                   8853: 		   $cucourseid%$cuname+
                   8854: 		   $cucourseid%$cudom);
                   8855:     }
                   8856:     return $return;
1.76      www      8857: }
                   8858: 
                   8859: sub receipt {
1.474     albertel 8860:     my ($part)=@_;
1.790     albertel 8861:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8862:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8863: }
1.260     ng       8864: 
1.790     albertel 8865: sub whichuser {
                   8866:     my ($passedsymb)=@_;
                   8867:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8868:     if (defined($env{'form.grade_symb'})) {
                   8869: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8870: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8871: 	if (!$allowed &&
                   8872: 	    exists($env{'request.course.sec'}) &&
                   8873: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8874: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8875: 			      '/'.$env{'request.course.sec'});
                   8876: 	}
                   8877: 	if ($allowed) {
                   8878: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8879: 	    $courseid=$tmp_courseid;
                   8880: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8881: 	    ($name)=&get_env_multiple('form.grade_username');
                   8882: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8883: 	}
                   8884:     }
                   8885:     if (!$passedsymb) {
                   8886: 	$symb=&symbread();
                   8887:     } else {
                   8888: 	$symb=$passedsymb;
                   8889:     }
                   8890:     $courseid=$env{'request.course.id'};
                   8891:     $domain=$env{'user.domain'};
                   8892:     $name=$env{'user.name'};
                   8893:     if ($name eq 'public' && $domain eq 'public') {
                   8894: 	if (!defined($env{'form.username'})) {
                   8895: 	    $env{'form.username'}.=time.rand(10000000);
                   8896: 	}
                   8897: 	$name.=$env{'form.username'};
                   8898:     }
                   8899:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8900: 
                   8901: }
                   8902: 
1.36      albertel 8903: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8904: # returns either the contents of the file or 
                   8905: # -1 if the file doesn't exist
1.481     raeburn  8906: #
                   8907: # if the target is a file that was uploaded via DOCS, 
                   8908: # a check will be made to see if a current copy exists on the local server,
                   8909: # if it does this will be served, otherwise a copy will be retrieved from
                   8910: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8911: # the local server.   
1.472     albertel 8912: 
1.36      albertel 8913: sub getfile {
1.538     albertel 8914:     my ($file) = @_;
1.609     banghart 8915:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8916:     &repcopy($file);
                   8917:     return &readfile($file);
                   8918: }
                   8919: 
                   8920: sub repcopy_userfile {
                   8921:     my ($file)=@_;
1.609     banghart 8922:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8923:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8924:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8925: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8926:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8927:     if (-e "$file") {
1.828     www      8928: # we already have a local copy, check it out
1.538     albertel 8929: 	my @fileinfo = stat($file);
1.828     www      8930: 	my $rtncode;
                   8931: 	my $info;
1.538     albertel 8932: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8933: 	if ($lwpresp ne 'ok') {
1.828     www      8934: # there is no such file anymore, even though we had a local copy
1.482     albertel 8935: 	    if ($rtncode eq '404') {
1.538     albertel 8936: 		unlink($file);
1.482     albertel 8937: 	    }
                   8938: 	    return -1;
                   8939: 	}
                   8940: 	if ($info < $fileinfo[9]) {
1.828     www      8941: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8942: 	    return 'ok';
1.828     www      8943: 	} else {
                   8944: # the file is outdated, get rid of it
                   8945: 	    unlink($file);
1.482     albertel 8946: 	}
1.828     www      8947:     }
                   8948: # one way or the other, at this point, we don't have the file
                   8949: # construct the correct path for the file
                   8950:     my @parts = ($cdom,$cnum); 
                   8951:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8952: 	push @parts, split(/\//,$1);
                   8953:     }
                   8954:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8955:     foreach my $part (@parts) {
                   8956: 	$path .= '/'.$part;
                   8957: 	if (!-e $path) {
                   8958: 	    mkdir($path,0770);
1.482     albertel 8959: 	}
                   8960:     }
1.828     www      8961: # now the path exists for sure
                   8962: # get a user agent
                   8963:     my $ua=new LWP::UserAgent;
                   8964:     my $transferfile=$file.'.in.transfer';
                   8965: # FIXME: this should flock
                   8966:     if (-e $transferfile) { return 'ok'; }
                   8967:     my $request;
                   8968:     $uri=~s/^\///;
1.980     raeburn  8969:     my $homeserver = &homeserver($cnum,$cdom);
                   8970:     my $protocol = $protocol{$homeserver};
                   8971:     $protocol = 'http' if ($protocol ne 'https');
                   8972:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8973:     my $response=$ua->request($request,$transferfile);
                   8974: # did it work?
                   8975:     if ($response->is_error()) {
                   8976: 	unlink($transferfile);
                   8977: 	&logthis("Userfile repcopy failed for $uri");
                   8978: 	return -1;
                   8979:     }
                   8980: # worked, rename the transfer file
                   8981:     rename($transferfile,$file);
1.607     raeburn  8982:     return 'ok';
1.481     raeburn  8983: }
                   8984: 
1.517     albertel 8985: sub tokenwrapper {
                   8986:     my $uri=shift;
1.980     raeburn  8987:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8988:     $uri=~s|^/||;
1.620     albertel 8989:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8990:     my $token=$1;
1.552     albertel 8991:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8992:     if ($udom && $uname && $file) {
                   8993: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8994:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8995:         my $homeserver = &homeserver($uname,$udom);
                   8996:         my $protocol = $protocol{$homeserver};
                   8997:         $protocol = 'http' if ($protocol ne 'https');
                   8998:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8999:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9000:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9001:     } else {
                   9002:         return '/adm/notfound.html';
                   9003:     }
                   9004: }
                   9005: 
1.828     www      9006: # call with reqtype HEAD: get last modification time
                   9007: # call with reqtype GET: get the file contents
                   9008: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9009: #
1.481     raeburn  9010: sub getuploaded {
                   9011:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9012:     $uri=~s/^\///;
1.980     raeburn  9013:     my $homeserver = &homeserver($cnum,$cdom);
                   9014:     my $protocol = $protocol{$homeserver};
                   9015:     $protocol = 'http' if ($protocol ne 'https');
                   9016:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9017:     my $ua=new LWP::UserAgent;
                   9018:     my $request=new HTTP::Request($reqtype,$uri);
                   9019:     my $response=$ua->request($request);
                   9020:     $$rtncode = $response->code;
1.482     albertel 9021:     if (! $response->is_success()) {
                   9022: 	return 'failed';
                   9023:     }      
                   9024:     if ($reqtype eq 'HEAD') {
1.486     www      9025: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9026:     } elsif ($reqtype eq 'GET') {
                   9027: 	$$info = $response->content;
1.472     albertel 9028:     }
1.482     albertel 9029:     return 'ok';
1.36      albertel 9030: }
                   9031: 
1.481     raeburn  9032: sub readfile {
                   9033:     my $file = shift;
                   9034:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9035:     my $fh;
                   9036:     open($fh,"<$file");
                   9037:     my $a='';
1.800     albertel 9038:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9039:     return $a;
                   9040: }
                   9041: 
1.36      albertel 9042: sub filelocation {
1.590     banghart 9043:     my ($dir,$file) = @_;
                   9044:     my $location;
                   9045:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9046: 
                   9047:     if ($file =~ m-^/adm/-) {
                   9048: 	$file=~s-^/adm/wrapper/-/-;
                   9049: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9050:     }
1.882     albertel 9051: 
1.590     banghart 9052:     if ($file=~m:^/~:) { # is a contruction space reference
                   9053:         $location = $file;
                   9054:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9055:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9056: 	# is a correct contruction space reference
                   9057:         $location = $file;
1.956     raeburn  9058:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9059:         $location = $file;
1.609     banghart 9060:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9061:         my ($udom,$uname,$filename)=
1.811     albertel 9062:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9063:         my $home=&homeserver($uname,$udom);
                   9064:         my $is_me=0;
                   9065:         my @ids=&current_machine_ids();
                   9066:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9067:         if ($is_me) {
1.955     raeburn  9068:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9069:         } else {
                   9070:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9071:   	      $udom.'/'.$uname.'/'.$filename;
                   9072:         }
1.882     albertel 9073:     } elsif ($file =~ m-^/adm/-) {
                   9074: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9075:     } else {
                   9076:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9077:         $file=~s:^/res/:/:;
                   9078:         if ( !( $file =~ m:^/:) ) {
                   9079:             $location = $dir. '/'.$file;
                   9080:         } else {
                   9081:             $location = '/home/httpd/html/res'.$file;
                   9082:         }
1.59      albertel 9083:     }
1.590     banghart 9084:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9085:     while ($location=~m{/\.\./}) {
                   9086: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9087: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9088: 	} else {
                   9089: 	    $location=~ s{/\.\./}{/}g;
                   9090: 	}
                   9091:     } #remove dir/..
1.590     banghart 9092:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9093:     return $location;
1.46      www      9094: }
1.36      albertel 9095: 
1.46      www      9096: sub hreflocation {
                   9097:     my ($dir,$file)=@_;
1.980     raeburn  9098:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9099: 	$file=filelocation($dir,$file);
1.700     albertel 9100:     } elsif ($file=~m-^/adm/-) {
                   9101: 	$file=~s-^/adm/wrapper/-/-;
                   9102: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9103:     }
                   9104:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9105: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9106:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9107: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9108:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9109: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9110: 	    -/uploaded/$1/$2/-x;
1.46      www      9111:     }
1.913     albertel 9112:     if ($file=~ m{^/userfiles/}) {
                   9113: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9114:     }
1.462     albertel 9115:     return $file;
1.465     albertel 9116: }
                   9117: 
                   9118: sub current_machine_domains {
1.853     albertel 9119:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9120: }
                   9121: 
                   9122: sub machine_domains {
                   9123:     my ($hostname) = @_;
1.465     albertel 9124:     my @domains;
1.838     albertel 9125:     my %hostname = &all_hostnames();
1.465     albertel 9126:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9127: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9128: 	if ($hostname eq $name) {
1.844     albertel 9129: 	    push(@domains,&host_domain($id));
1.465     albertel 9130: 	}
                   9131:     }
                   9132:     return @domains;
                   9133: }
                   9134: 
                   9135: sub current_machine_ids {
1.853     albertel 9136:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9137: }
                   9138: 
                   9139: sub machine_ids {
                   9140:     my ($hostname) = @_;
                   9141:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9142:     my @ids;
1.888     albertel 9143:     my %name_to_host = &all_names();
1.889     albertel 9144:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9145: 	return @{ $name_to_host{$hostname} };
                   9146:     }
                   9147:     return;
1.31      www      9148: }
                   9149: 
1.824     raeburn  9150: sub additional_machine_domains {
                   9151:     my @domains;
                   9152:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9153:     while( my $line = <$fh>) {
                   9154:         $line =~ s/\s//g;
                   9155:         push(@domains,$line);
                   9156:     }
                   9157:     return @domains;
                   9158: }
                   9159: 
                   9160: sub default_login_domain {
                   9161:     my $domain = $perlvar{'lonDefDomain'};
                   9162:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9163:     foreach my $posdom (&current_machine_domains(),
                   9164:                         &additional_machine_domains()) {
                   9165:         if (lc($posdom) eq lc($testdomain)) {
                   9166:             $domain=$posdom;
                   9167:             last;
                   9168:         }
                   9169:     }
                   9170:     return $domain;
                   9171: }
                   9172: 
1.31      www      9173: # ------------------------------------------------------------- Declutters URLs
                   9174: 
                   9175: sub declutter {
                   9176:     my $thisfn=shift;
1.569     albertel 9177:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9178:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9179:     $thisfn=~s/^\///;
1.697     albertel 9180:     $thisfn=~s|^adm/wrapper/||;
                   9181:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9182:     $thisfn=~s/^res\///;
1.1032    raeburn  9183:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9184:         $thisfn=~s/\?.+$//;
                   9185:     }
1.268     www      9186:     return $thisfn;
                   9187: }
                   9188: 
                   9189: # ------------------------------------------------------------- Clutter up URLs
                   9190: 
                   9191: sub clutter {
                   9192:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9193:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9194: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9195:        $thisfn='/res'.$thisfn; 
                   9196:     }
1.1031    raeburn  9197:     if ($thisfn !~m|^/adm|) {
                   9198: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9199: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9200: 	} else {
                   9201: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9202: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9203: 	    if ($embstyle eq 'ssi'
                   9204: 		|| ($embstyle eq 'hdn')
                   9205: 		|| ($embstyle eq 'rat')
                   9206: 		|| ($embstyle eq 'prv')
                   9207: 		|| ($embstyle eq 'ign')) {
                   9208: 		#do nothing with these
                   9209: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9210: 		|| ($embstyle eq 'emb')
                   9211: 		|| ($embstyle eq 'wrp')) {
                   9212: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9213: 	    } elsif ($embstyle eq 'unk'
                   9214: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9215: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9216: 	    } else {
1.718     www      9217: #		&logthis("Got a blank emb style");
1.695     albertel 9218: 	    }
1.694     albertel 9219: 	}
                   9220:     }
1.31      www      9221:     return $thisfn;
1.12      www      9222: }
                   9223: 
1.787     albertel 9224: sub clutter_with_no_wrapper {
                   9225:     my $uri = &clutter(shift);
                   9226:     if ($uri =~ m-^/adm/-) {
                   9227: 	$uri =~ s-^/adm/wrapper/-/-;
                   9228: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9229:     }
                   9230:     return $uri;
                   9231: }
                   9232: 
1.557     albertel 9233: sub freeze_escape {
                   9234:     my ($value)=@_;
                   9235:     if (ref($value)) {
                   9236: 	$value=&nfreeze($value);
                   9237: 	return '__FROZEN__'.&escape($value);
                   9238:     }
                   9239:     return &escape($value);
                   9240: }
                   9241: 
1.11      www      9242: 
1.557     albertel 9243: sub thaw_unescape {
                   9244:     my ($value)=@_;
                   9245:     if ($value =~ /^__FROZEN__/) {
                   9246: 	substr($value,0,10,undef);
                   9247: 	$value=&unescape($value);
                   9248: 	return &thaw($value);
                   9249:     }
                   9250:     return &unescape($value);
                   9251: }
                   9252: 
1.436     albertel 9253: sub correct_line_ends {
                   9254:     my ($result)=@_;
                   9255:     $$result =~s/\r\n/\n/mg;
                   9256:     $$result =~s/\r/\n/mg;
1.415     albertel 9257: }
1.1       albertel 9258: # ================================================================ Main Program
                   9259: 
1.184     www      9260: sub goodbye {
1.204     albertel 9261:    &logthis("Starting Shut down");
1.443     albertel 9262: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9263:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9264: #converted
1.599     albertel 9265: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9266:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9267: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9268: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9269: #1.1 only
1.870     albertel 9270: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9271: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9272: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9273: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9274:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9275:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9276:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9277:    &flushcourselogs();
                   9278:    &logthis("Shutting down");
                   9279: }
                   9280: 
1.852     albertel 9281: sub get_dns {
1.869     albertel 9282:     my ($url,$func,$ignore_cache) = @_;
                   9283:     if (!$ignore_cache) {
                   9284: 	my ($content,$cached)=
                   9285: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9286: 	if ($cached) {
                   9287: 	    &$func($content);
                   9288: 	    return;
                   9289: 	}
                   9290:     }
                   9291: 
                   9292:     my %alldns;
1.852     albertel 9293:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9294:     foreach my $dns (<$config>) {
                   9295: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9296:         my $line = $1;
                   9297:         my ($host,$protocol) = split(/:/,$line);
                   9298:         if ($protocol ne 'https') {
                   9299:             $protocol = 'http';
                   9300:         }
                   9301: 	$alldns{$host} = $protocol;
1.869     albertel 9302:     }
                   9303:     while (%alldns) {
                   9304: 	my ($dns) = keys(%alldns);
1.852     albertel 9305: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9306: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9307: 	my $response=$ua->request($request);
1.979     raeburn  9308:         delete($alldns{$dns});
1.852     albertel 9309: 	next if ($response->is_error());
                   9310: 	my @content = split("\n",$response->content);
1.869     albertel 9311: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9312: 	&$func(\@content);
1.869     albertel 9313: 	return;
1.852     albertel 9314:     }
                   9315:     close($config);
1.871     albertel 9316:     my $which = (split('/',$url))[3];
                   9317:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9318:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9319:     my @content = <$config>;
                   9320:     &$func(\@content);
                   9321:     return;
1.852     albertel 9322: }
1.327     albertel 9323: # ------------------------------------------------------------ Read domain file
                   9324: {
1.852     albertel 9325:     my $loaded;
1.846     albertel 9326:     my %domain;
                   9327: 
1.852     albertel 9328:     sub parse_domain_tab {
                   9329: 	my ($lines) = @_;
                   9330: 	foreach my $line (@$lines) {
                   9331: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9332: 
1.846     albertel 9333: 	    chomp($line);
1.852     albertel 9334: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9335: 	    my %this_domain;
                   9336: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9337: 			       'lang_def', 'city', 'longi', 'lati',
                   9338: 			       'primary') {
                   9339: 		$this_domain{$field} = shift(@elements);
                   9340: 	    }
                   9341: 	    $domain{$name} = \%this_domain;
1.852     albertel 9342: 	}
                   9343:     }
1.864     albertel 9344: 
                   9345:     sub reset_domain_info {
                   9346: 	undef($loaded);
                   9347: 	undef(%domain);
                   9348:     }
                   9349: 
1.852     albertel 9350:     sub load_domain_tab {
1.869     albertel 9351: 	my ($ignore_cache) = @_;
                   9352: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9353: 	my $fh;
                   9354: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9355: 	    my @lines = <$fh>;
                   9356: 	    &parse_domain_tab(\@lines);
1.448     albertel 9357: 	}
1.852     albertel 9358: 	close($fh);
                   9359: 	$loaded = 1;
1.327     albertel 9360:     }
1.846     albertel 9361: 
                   9362:     sub domain {
1.852     albertel 9363: 	&load_domain_tab() if (!$loaded);
                   9364: 
1.846     albertel 9365: 	my ($name,$what) = @_;
                   9366: 	return if ( !exists($domain{$name}) );
                   9367: 
                   9368: 	if (!$what) {
                   9369: 	    return $domain{$name}{'description'};
                   9370: 	}
                   9371: 	return $domain{$name}{$what};
                   9372:     }
1.974     raeburn  9373: 
                   9374:     sub domain_info {
                   9375:         &load_domain_tab() if (!$loaded);
                   9376:         return %domain;
                   9377:     }
                   9378: 
1.327     albertel 9379: }
                   9380: 
                   9381: 
1.1       albertel 9382: # ------------------------------------------------------------- Read hosts file
                   9383: {
1.838     albertel 9384:     my %hostname;
1.844     albertel 9385:     my %hostdom;
1.845     albertel 9386:     my %libserv;
1.852     albertel 9387:     my $loaded;
1.888     albertel 9388:     my %name_to_host;
1.852     albertel 9389: 
                   9390:     sub parse_hosts_tab {
                   9391: 	my ($file) = @_;
                   9392: 	foreach my $configline (@$file) {
                   9393: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9394: 	    next if ($configline =~ /^\^/);
                   9395: 	    chomp($configline);
1.968     raeburn  9396: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9397: 	    $name=~s/\s//g;
                   9398: 	    if ($id && $domain && $role && $name) {
                   9399: 		$hostname{$id}=$name;
1.888     albertel 9400: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9401: 		$hostdom{$id}=$domain;
                   9402: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9403:                 if (defined($protocol)) {
                   9404:                     if ($protocol eq 'https') {
                   9405:                         $protocol{$id} = $protocol;
                   9406:                     } else {
                   9407:                         $protocol{$id} = 'http'; 
                   9408:                     }
1.968     raeburn  9409:                 } else {
1.969     raeburn  9410:                     $protocol{$id} = 'http';
1.968     raeburn  9411:                 }
1.852     albertel 9412: 	    }
                   9413: 	}
                   9414:     }
1.864     albertel 9415:     
                   9416:     sub reset_hosts_info {
1.897     albertel 9417: 	&purge_remembered();
1.864     albertel 9418: 	&reset_domain_info();
                   9419: 	&reset_hosts_ip_info();
1.892     albertel 9420: 	undef(%name_to_host);
1.864     albertel 9421: 	undef(%hostname);
                   9422: 	undef(%hostdom);
                   9423: 	undef(%libserv);
                   9424: 	undef($loaded);
                   9425:     }
1.1       albertel 9426: 
1.852     albertel 9427:     sub load_hosts_tab {
1.869     albertel 9428: 	my ($ignore_cache) = @_;
                   9429: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9430: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9431: 	my @config = <$config>;
                   9432: 	&parse_hosts_tab(\@config);
                   9433: 	close($config);
                   9434: 	$loaded=1;
1.1       albertel 9435:     }
1.852     albertel 9436: 
1.838     albertel 9437:     sub hostname {
1.852     albertel 9438: 	&load_hosts_tab() if (!$loaded);
                   9439: 
1.838     albertel 9440: 	my ($lonid) = @_;
                   9441: 	return $hostname{$lonid};
                   9442:     }
1.845     albertel 9443: 
1.838     albertel 9444:     sub all_hostnames {
1.852     albertel 9445: 	&load_hosts_tab() if (!$loaded);
                   9446: 
1.838     albertel 9447: 	return %hostname;
                   9448:     }
1.845     albertel 9449: 
1.888     albertel 9450:     sub all_names {
                   9451: 	&load_hosts_tab() if (!$loaded);
                   9452: 
                   9453: 	return %name_to_host;
                   9454:     }
                   9455: 
1.974     raeburn  9456:     sub all_host_domain {
                   9457:         &load_hosts_tab() if (!$loaded);
                   9458:         return %hostdom;
                   9459:     }
                   9460: 
1.845     albertel 9461:     sub is_library {
1.852     albertel 9462: 	&load_hosts_tab() if (!$loaded);
                   9463: 
1.845     albertel 9464: 	return exists($libserv{$_[0]});
                   9465:     }
                   9466: 
                   9467:     sub all_library {
1.852     albertel 9468: 	&load_hosts_tab() if (!$loaded);
                   9469: 
1.845     albertel 9470: 	return %libserv;
                   9471:     }
                   9472: 
1.841     albertel 9473:     sub get_servers {
1.852     albertel 9474: 	&load_hosts_tab() if (!$loaded);
                   9475: 
1.841     albertel 9476: 	my ($domain,$type) = @_;
                   9477: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9478: 	                                          : %hostname;
                   9479: 	my %result;
1.842     albertel 9480: 	if (ref($domain) eq 'ARRAY') {
                   9481: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9482: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9483: 		    $result{$host} = $hostname;
                   9484: 		}
                   9485: 	    }
                   9486: 	} else {
                   9487: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9488: 		if ($hostdom{$host} eq $domain) {
                   9489: 		    $result{$host} = $hostname;
                   9490: 		}
1.841     albertel 9491: 	    }
                   9492: 	}
                   9493: 	return %result;
                   9494:     }
1.845     albertel 9495: 
1.844     albertel 9496:     sub host_domain {
1.852     albertel 9497: 	&load_hosts_tab() if (!$loaded);
                   9498: 
1.844     albertel 9499: 	my ($lonid) = @_;
                   9500: 	return $hostdom{$lonid};
                   9501:     }
                   9502: 
1.841     albertel 9503:     sub all_domains {
1.852     albertel 9504: 	&load_hosts_tab() if (!$loaded);
                   9505: 
1.841     albertel 9506: 	my %seen;
                   9507: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9508: 	return @uniq;
                   9509:     }
1.1       albertel 9510: }
                   9511: 
1.847     albertel 9512: { 
                   9513:     my %iphost;
1.856     albertel 9514:     my %name_to_ip;
                   9515:     my %lonid_to_ip;
1.869     albertel 9516: 
1.847     albertel 9517:     sub get_hosts_from_ip {
                   9518: 	my ($ip) = @_;
                   9519: 	my %iphosts = &get_iphost();
                   9520: 	if (ref($iphosts{$ip})) {
                   9521: 	    return @{$iphosts{$ip}};
                   9522: 	}
                   9523: 	return;
1.839     albertel 9524:     }
1.864     albertel 9525:     
                   9526:     sub reset_hosts_ip_info {
                   9527: 	undef(%iphost);
                   9528: 	undef(%name_to_ip);
                   9529: 	undef(%lonid_to_ip);
                   9530:     }
1.856     albertel 9531: 
                   9532:     sub get_host_ip {
                   9533: 	my ($lonid) = @_;
                   9534: 	if (exists($lonid_to_ip{$lonid})) {
                   9535: 	    return $lonid_to_ip{$lonid};
                   9536: 	}
                   9537: 	my $name=&hostname($lonid);
                   9538:    	my $ip = gethostbyname($name);
                   9539: 	return if (!$ip || length($ip) ne 4);
                   9540: 	$ip=inet_ntoa($ip);
                   9541: 	$name_to_ip{$name}   = $ip;
                   9542: 	$lonid_to_ip{$lonid} = $ip;
                   9543: 	return $ip;
                   9544:     }
1.847     albertel 9545:     
                   9546:     sub get_iphost {
1.869     albertel 9547: 	my ($ignore_cache) = @_;
1.894     albertel 9548: 
1.869     albertel 9549: 	if (!$ignore_cache) {
                   9550: 	    if (%iphost) {
                   9551: 		return %iphost;
                   9552: 	    }
                   9553: 	    my ($ip_info,$cached)=
                   9554: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9555: 	    if ($cached) {
                   9556: 		%iphost      = %{$ip_info->[0]};
                   9557: 		%name_to_ip  = %{$ip_info->[1]};
                   9558: 		%lonid_to_ip = %{$ip_info->[2]};
                   9559: 		return %iphost;
                   9560: 	    }
                   9561: 	}
1.894     albertel 9562: 
                   9563: 	# get yesterday's info for fallback
                   9564: 	my %old_name_to_ip;
                   9565: 	my ($ip_info,$cached)=
                   9566: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9567: 	if ($cached) {
                   9568: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9569: 	}
                   9570: 
1.888     albertel 9571: 	my %name_to_host = &all_names();
                   9572: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9573: 	    my $ip;
                   9574: 	    if (!exists($name_to_ip{$name})) {
                   9575: 		$ip = gethostbyname($name);
                   9576: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9577: 		    if (defined($old_name_to_ip{$name})) {
                   9578: 			$ip = $old_name_to_ip{$name};
                   9579: 			&logthis("Can't find $name defaulting to old $ip");
                   9580: 		    } else {
                   9581: 			&logthis("Name $name no IP found");
                   9582: 			next;
                   9583: 		    }
                   9584: 		} else {
                   9585: 		    $ip=inet_ntoa($ip);
1.847     albertel 9586: 		}
                   9587: 		$name_to_ip{$name} = $ip;
                   9588: 	    } else {
                   9589: 		$ip = $name_to_ip{$name};
1.653     albertel 9590: 	    }
1.888     albertel 9591: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9592: 		$lonid_to_ip{$id} = $ip;
                   9593: 	    }
                   9594: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9595: 	}
1.869     albertel 9596: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9597: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9598: 				      48*60*60);
1.869     albertel 9599: 
1.847     albertel 9600: 	return %iphost;
1.598     albertel 9601:     }
                   9602: 
1.992     raeburn  9603:     #
                   9604:     #  Given a DNS returns the loncapa host name for that DNS 
                   9605:     # 
                   9606:     sub host_from_dns {
                   9607:         my ($dns) = @_;
                   9608:         my @hosts;
                   9609:         my $ip;
                   9610: 
1.993     raeburn  9611:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9612:             $ip = $name_to_ip{$dns};
                   9613:         }
                   9614:         if (!$ip) {
                   9615:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9616:             if (length($ip) == 4) { 
                   9617: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9618:             }
                   9619:         }
                   9620:         if ($ip) {
                   9621: 	    @hosts = get_hosts_from_ip($ip);
                   9622: 	    return $hosts[0];
                   9623:         }
                   9624:         return undef;
1.986     foxr     9625:     }
1.992     raeburn  9626: 
1.986     foxr     9627: }
                   9628: 
1.862     albertel 9629: BEGIN {
                   9630: 
                   9631: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9632:     unless ($readit) {
                   9633: {
                   9634:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9635:     %perlvar = (%perlvar,%{$configvars});
                   9636: }
                   9637: 
                   9638: 
1.1       albertel 9639: # ------------------------------------------------------ Read spare server file
                   9640: {
1.448     albertel 9641:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9642: 
                   9643:     while (my $configline=<$config>) {
                   9644:        chomp($configline);
1.284     matthew  9645:        if ($configline) {
1.784     albertel 9646: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9647: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9648: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9649:        }
                   9650:     }
1.448     albertel 9651:     close($config);
1.1       albertel 9652: }
1.11      www      9653: # ------------------------------------------------------------ Read permissions
                   9654: {
1.448     albertel 9655:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9656: 
                   9657:     while (my $configline=<$config>) {
1.448     albertel 9658: 	chomp($configline);
                   9659: 	if ($configline) {
                   9660: 	    my ($role,$perm)=split(/ /,$configline);
                   9661: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9662: 	}
1.11      www      9663:     }
1.448     albertel 9664:     close($config);
1.11      www      9665: }
                   9666: 
                   9667: # -------------------------------------------- Read plain texts for permissions
                   9668: {
1.448     albertel 9669:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9670: 
                   9671:     while (my $configline=<$config>) {
1.448     albertel 9672: 	chomp($configline);
                   9673: 	if ($configline) {
1.742     raeburn  9674: 	    my ($short,@plain)=split(/:/,$configline);
                   9675:             %{$prp{$short}} = ();
                   9676: 	    if (@plain > 0) {
                   9677:                 $prp{$short}{'std'} = $plain[0];
                   9678:                 for (my $i=1; $i<@plain; $i++) {
                   9679:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9680:                 }
                   9681:             }
1.448     albertel 9682: 	}
1.135     www      9683:     }
1.448     albertel 9684:     close($config);
1.135     www      9685: }
                   9686: 
                   9687: # ---------------------------------------------------------- Read package table
                   9688: {
1.448     albertel 9689:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9690: 
                   9691:     while (my $configline=<$config>) {
1.483     albertel 9692: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9693: 	chomp($configline);
                   9694: 	my ($short,$plain)=split(/:/,$configline);
                   9695: 	my ($pack,$name)=split(/\&/,$short);
                   9696: 	if ($plain ne '') {
                   9697: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9698: 	    $packagetab{$short}=$plain; 
                   9699: 	}
1.11      www      9700:     }
1.448     albertel 9701:     close($config);
1.329     matthew  9702: }
                   9703: 
                   9704: # ------------- set up temporary directory
                   9705: {
                   9706:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9707: 
1.11      www      9708: }
                   9709: 
1.794     albertel 9710: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9711: 				'compress_threshold'=> 20_000,
                   9712:  			        });
1.185     www      9713: 
1.281     www      9714: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9715: $dumpcount=0;
1.958     www      9716: $locknum=0;
1.22      www      9717: 
1.163     harris41 9718: &logtouch();
1.672     albertel 9719: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9720: $readit=1;
1.564     albertel 9721:     {
                   9722: 	use integer;
                   9723: 	my $test=(2**32)+1;
1.568     albertel 9724: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9725: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9726:     }
1.195     www      9727: }
1.1       albertel 9728: }
1.179     www      9729: 
1.1       albertel 9730: 1;
1.191     harris41 9731: __END__
                   9732: 
1.243     albertel 9733: =pod
                   9734: 
1.191     harris41 9735: =head1 NAME
                   9736: 
1.243     albertel 9737: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9738: 
                   9739: =head1 SYNOPSIS
                   9740: 
1.243     albertel 9741: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9742: 
                   9743:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9744: 
1.243     albertel 9745: Common parameters:
                   9746: 
                   9747: =over 4
                   9748: 
                   9749: =item *
                   9750: 
                   9751: $uname : an internal username (if $cname expecting a course Id specifically)
                   9752: 
                   9753: =item *
                   9754: 
                   9755: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9756: 
                   9757: =item *
                   9758: 
                   9759: $symb : a resource instance identifier
                   9760: 
                   9761: =item *
                   9762: 
                   9763: $namespace : the name of a .db file that contains the data needed or
                   9764: being set.
                   9765: 
                   9766: =back
                   9767: 
1.394     bowersj2 9768: =head1 OVERVIEW
1.191     harris41 9769: 
1.394     bowersj2 9770: lonnet provides subroutines which interact with the
                   9771: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9772: about classes, users, and resources.
1.243     albertel 9773: 
                   9774: For many of these objects you can also use this to store data about
                   9775: them or modify them in various ways.
1.191     harris41 9776: 
1.394     bowersj2 9777: =head2 Symbs
1.191     harris41 9778: 
1.394     bowersj2 9779: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9780: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9781: map, the resource number of the resource in the map, and the URL of
                   9782: the resource itself. The latter is somewhat redundant, but might help
                   9783: if maps change.
                   9784: 
                   9785: An example is
                   9786: 
                   9787:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9788: 
                   9789: The respective map entry is
                   9790: 
                   9791:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9792:   title="Problem 2">
                   9793:  </resource>
                   9794: 
                   9795: Symbs are used by the random number generator, as well as to store and
                   9796: restore data specific to a certain instance of for example a problem.
                   9797: 
                   9798: =head2 Storing And Retrieving Data
                   9799: 
                   9800: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9801: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9802: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9803: is is the non-critical message twin of cstore. These functions are for
                   9804: handlers to store a perl hash to a user's permanent data space in an
                   9805: easy manner, and to retrieve it again on another call. It is expected
                   9806: that a handler would use this once at the beginning to retrieve data,
                   9807: and then again once at the end to send only the new data back.
                   9808: 
                   9809: The data is stored in the user's data directory on the user's
                   9810: homeserver under the ID of the course.
                   9811: 
                   9812: The hash that is returned by restore will have all of the previous
                   9813: value for all of the elements of the hash.
                   9814: 
                   9815: Example:
                   9816: 
                   9817:  #creating a hash
                   9818:  my %hash;
                   9819:  $hash{'foo'}='bar';
                   9820: 
                   9821:  #storing it
                   9822:  &Apache::lonnet::cstore(\%hash);
                   9823: 
                   9824:  #changing a value
                   9825:  $hash{'foo'}='notbar';
                   9826: 
                   9827:  #adding a new value
                   9828:  $hash{'bar'}='foo';
                   9829:  &Apache::lonnet::cstore(\%hash);
                   9830: 
                   9831:  #retrieving the hash
                   9832:  my %history=&Apache::lonnet::restore();
                   9833: 
                   9834:  #print the hash
                   9835:  foreach my $key (sort(keys(%history))) {
                   9836:    print("\%history{$key} = $history{$key}");
                   9837:  }
                   9838: 
                   9839: Will print out:
1.191     harris41 9840: 
1.394     bowersj2 9841:  %history{1:foo} = bar
                   9842:  %history{1:keys} = foo:timestamp
                   9843:  %history{1:timestamp} = 990455579
                   9844:  %history{2:bar} = foo
                   9845:  %history{2:foo} = notbar
                   9846:  %history{2:keys} = foo:bar:timestamp
                   9847:  %history{2:timestamp} = 990455580
                   9848:  %history{bar} = foo
                   9849:  %history{foo} = notbar
                   9850:  %history{timestamp} = 990455580
                   9851:  %history{version} = 2
                   9852: 
                   9853: Note that the special hash entries C<keys>, C<version> and
                   9854: C<timestamp> were added to the hash. C<version> will be equal to the
                   9855: total number of versions of the data that have been stored. The
                   9856: C<timestamp> attribute will be the UNIX time the hash was
                   9857: stored. C<keys> is available in every historical section to list which
                   9858: keys were added or changed at a specific historical revision of a
                   9859: hash.
                   9860: 
                   9861: B<Warning>: do not store the hash that restore returns directly. This
                   9862: will cause a mess since it will restore the historical keys as if the
                   9863: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9864: 
1.394     bowersj2 9865: Calling convention:
1.191     harris41 9866: 
1.394     bowersj2 9867:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9868:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9869: 
1.394     bowersj2 9870: For more detailed information, see lonnet specific documentation.
1.191     harris41 9871: 
1.394     bowersj2 9872: =head1 RETURN MESSAGES
1.191     harris41 9873: 
1.394     bowersj2 9874: =over 4
1.191     harris41 9875: 
1.394     bowersj2 9876: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9877: 
1.394     bowersj2 9878: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9879: when the connection is brought back up
1.191     harris41 9880: 
1.394     bowersj2 9881: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9882: for later delivery
1.191     harris41 9883: 
1.967     bisitz   9884: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9885: 
1.394     bowersj2 9886: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9887: that was requested
1.191     harris41 9888: 
1.243     albertel 9889: =back
1.191     harris41 9890: 
1.243     albertel 9891: =head1 PUBLIC SUBROUTINES
1.191     harris41 9892: 
1.243     albertel 9893: =head2 Session Environment Functions
1.191     harris41 9894: 
1.243     albertel 9895: =over 4
1.191     harris41 9896: 
1.394     bowersj2 9897: =item * 
                   9898: X<appenv()>
1.949     raeburn  9899: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9900: the user envirnoment file, and will be restored for each access this
1.620     albertel 9901: user makes during this session, also modifies the %env for the current
1.949     raeburn  9902: process. Optional rolesarrayref - if defined contains a reference to an array
                   9903: of roles which are exempt from the restriction on modifying user.role entries 
                   9904: in the user's environment.db and in %env.    
1.191     harris41 9905: 
                   9906: =item *
1.394     bowersj2 9907: X<delenv()>
1.987     raeburn  9908: B<delenv($delthis,$regexp)>: removes all items from the session
                   9909: environment file that begin with $delthis. If the 
                   9910: optional second arg - $regexp - is true, $delthis is treated as a 
                   9911: regular expression, otherwise \Q$delthis\E is used. 
                   9912: The values are also deleted from the current processes %env.
1.191     harris41 9913: 
1.795     albertel 9914: =item * get_env_multiple($name) 
                   9915: 
                   9916: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9917: values may be defined and end up as an array ref.
                   9918: 
                   9919: returns an array of values
                   9920: 
1.243     albertel 9921: =back
                   9922: 
                   9923: =head2 User Information
1.191     harris41 9924: 
1.243     albertel 9925: =over 4
1.191     harris41 9926: 
                   9927: =item *
1.394     bowersj2 9928: X<queryauthenticate()>
                   9929: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9930: authentication scheme
                   9931: 
                   9932: =item *
1.394     bowersj2 9933: X<authenticate()>
                   9934: B<authenticate($uname,$upass,$udom)>: try to
                   9935: authenticate user from domain's lib servers (first use the current
                   9936: one). C<$upass> should be the users password.
1.191     harris41 9937: 
                   9938: =item *
1.394     bowersj2 9939: X<homeserver()>
                   9940: B<homeserver($uname,$udom)>: find the server which has
                   9941: the user's directory and files (there must be only one), this caches
                   9942: the answer, and also caches if there is a borken connection.
1.191     harris41 9943: 
                   9944: =item *
1.394     bowersj2 9945: X<idget()>
                   9946: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9947: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9948: username, and only 1 username per ID in a specific domain) (returns
                   9949: hash: id=>name,id=>name)
1.191     harris41 9950: 
                   9951: =item *
1.394     bowersj2 9952: X<idrget()>
                   9953: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9954: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9955: 
                   9956: =item *
1.394     bowersj2 9957: X<idput()>
                   9958: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9959: 
                   9960: =item *
1.394     bowersj2 9961: X<rolesinit()>
                   9962: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9963: 
                   9964: =item *
1.551     albertel 9965: X<getsection()>
                   9966: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9967: course $cname, return section name/number or '' for "not in course"
                   9968: and '-1' for "no section"
                   9969: 
                   9970: =item *
1.394     bowersj2 9971: X<userenvironment()>
                   9972: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9973: passed in @what from the requested user's environment, returns a hash
                   9974: 
1.858     raeburn  9975: =item * 
                   9976: X<userlog_query()>
1.859     albertel 9977: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9978: activity.log file. %filters defines filters applied when parsing the
                   9979: log file. These can be start or end timestamps, or the type of action
                   9980: - log to look for Login or Logout events, check for Checkin or
                   9981: Checkout, role for role selection. The response is in the form
                   9982: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9983: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9984: 
1.243     albertel 9985: =back
                   9986: 
                   9987: =head2 User Roles
                   9988: 
                   9989: =over 4
                   9990: 
                   9991: =item *
                   9992: 
1.810     raeburn  9993: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9994:  F: full access
                   9995:  U,I,K: authentication modes (cxx only)
                   9996:  '': forbidden
                   9997:  1: user needs to choose course
                   9998:  2: browse allowed
1.766     albertel 9999:  A: passphrase authentication needed
1.243     albertel 10000: 
                   10001: =item *
                   10002: 
                   10003: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10004: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10005: and course level
                   10006: 
                   10007: =item *
                   10008: 
1.988     raeburn  10009: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10010: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10011: $type is Course (default) or Community.
1.988     raeburn  10012: If $forcedefault evaluates to true, text returned will be default 
                   10013: text for $type. Otherwise, if this is a course, the text returned 
                   10014: will be a custom name for the role (if defined in the course's 
                   10015: environment).  If no custom name is defined the default is returned.
                   10016:    
1.832     raeburn  10017: =item *
                   10018: 
1.935     raeburn  10019: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10020: All arguments are optional. Returns a hash of a roles, either for
                   10021: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10022: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10023: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10024: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10025: For each key, value is set to colon-separated start and end times for
                   10026: the role.  If no username and domain are specified, will default to
1.934     raeburn  10027: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10028: of role statuses (active, future or previous), roles 
                   10029: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10030: to restrict the list of roles reported. If no array ref is 
                   10031: provided for types, will default to return only active roles.
1.834     albertel 10032: 
1.243     albertel 10033: =back
                   10034: 
                   10035: =head2 User Modification
                   10036: 
                   10037: =over 4
                   10038: 
                   10039: =item *
                   10040: 
1.957     raeburn  10041: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10042: user for the level given by URL.  Optional start and end dates (leave empty
                   10043: string or zero for "no date")
1.191     harris41 10044: 
                   10045: =item *
                   10046: 
1.243     albertel 10047: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10048: change a users, password, possible return values are: ok,
                   10049: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10050: refused
1.191     harris41 10051: 
                   10052: =item *
                   10053: 
1.243     albertel 10054: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10055: 
                   10056: =item *
                   10057: 
1.963     raeburn  10058: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   10059:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 10060: modify user
1.191     harris41 10061: 
                   10062: =item *
                   10063: 
1.286     matthew  10064: modifystudent
                   10065: 
1.957     raeburn  10066: modify a student's enrollment and identification information.
1.286     matthew  10067: The course id is resolved based on the current users environment.  
                   10068: This means the envoking user must be a course coordinator or otherwise
                   10069: associated with a course.
                   10070: 
1.297     matthew  10071: This call is essentially a wrapper for lonnet::modifyuser and
                   10072: lonnet::modify_student_enrollment
1.286     matthew  10073: 
                   10074: Inputs: 
                   10075: 
                   10076: =over 4
                   10077: 
1.957     raeburn  10078: =item B<$udom> Student's loncapa domain
1.286     matthew  10079: 
1.957     raeburn  10080: =item B<$uname> Student's loncapa login name
1.286     matthew  10081: 
1.964     bisitz   10082: =item B<$uid> Student/Employee ID
1.286     matthew  10083: 
1.957     raeburn  10084: =item B<$umode> Student's authentication mode
1.286     matthew  10085: 
1.957     raeburn  10086: =item B<$upass> Student's password
1.286     matthew  10087: 
1.957     raeburn  10088: =item B<$first> Student's first name
1.286     matthew  10089: 
1.957     raeburn  10090: =item B<$middle> Student's middle name
1.286     matthew  10091: 
1.957     raeburn  10092: =item B<$last> Student's last name
1.286     matthew  10093: 
1.957     raeburn  10094: =item B<$gene> Student's generation
1.286     matthew  10095: 
1.957     raeburn  10096: =item B<$usec> Student's section in course
1.286     matthew  10097: 
                   10098: =item B<$end> Unix time of the roles expiration
                   10099: 
                   10100: =item B<$start> Unix time of the roles start date
                   10101: 
                   10102: =item B<$forceid> If defined, allow $uid to be changed
                   10103: 
                   10104: =item B<$desiredhome> server to use as home server for student
                   10105: 
1.957     raeburn  10106: =item B<$email> Student's permanent e-mail address
                   10107: 
                   10108: =item B<$type> Type of enrollment (auto or manual)
                   10109: 
1.963     raeburn  10110: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10111: 
                   10112: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10113: 
1.963     raeburn  10114: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10115: 
1.963     raeburn  10116: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10117: 
1.963     raeburn  10118: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10119: 
1.286     matthew  10120: =back
1.297     matthew  10121: 
                   10122: =item *
                   10123: 
                   10124: modify_student_enrollment
                   10125: 
                   10126: Change a students enrollment status in a class.  The environment variable
                   10127: 'role.request.course' must be defined for this function to proceed.
                   10128: 
                   10129: Inputs:
                   10130: 
                   10131: =over 4
                   10132: 
                   10133: =item $udom, students domain
                   10134: 
                   10135: =item $uname, students name
                   10136: 
                   10137: =item $uid, students user id
                   10138: 
                   10139: =item $first, students first name
                   10140: 
                   10141: =item $middle
                   10142: 
                   10143: =item $last
                   10144: 
                   10145: =item $gene
                   10146: 
                   10147: =item $usec
                   10148: 
                   10149: =item $end
                   10150: 
                   10151: =item $start
                   10152: 
1.957     raeburn  10153: =item $type
                   10154: 
                   10155: =item $locktype
                   10156: 
                   10157: =item $cid
                   10158: 
                   10159: =item $selfenroll
                   10160: 
                   10161: =item $context
                   10162: 
1.297     matthew  10163: =back
                   10164: 
1.191     harris41 10165: 
                   10166: =item *
                   10167: 
1.243     albertel 10168: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10169: custom role; give a custom role to a user for the level given by URL.  Specify
                   10170: name and domain of role author, and role name
1.191     harris41 10171: 
                   10172: =item *
                   10173: 
1.243     albertel 10174: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10175: 
                   10176: =item *
                   10177: 
1.243     albertel 10178: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10179: 
                   10180: =back
                   10181: 
                   10182: =head2 Course Infomation
                   10183: 
                   10184: =over 4
1.191     harris41 10185: 
                   10186: =item *
                   10187: 
1.631     albertel 10188: coursedescription($courseid) : returns a hash of information about the
                   10189: specified course id, including all environment settings for the
                   10190: course, the description of the course will be in the hash under the
                   10191: key 'description'
1.191     harris41 10192: 
                   10193: =item *
                   10194: 
1.624     albertel 10195: resdata($name,$domain,$type,@which) : request for current parameter
                   10196: setting for a specific $type, where $type is either 'course' or 'user',
                   10197: @what should be a list of parameters to ask about. This routine caches
                   10198: answers for 5 minutes.
1.243     albertel 10199: 
1.877     foxr     10200: =item *
                   10201: 
                   10202: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10203: data base, returning a hash that is keyed by the resource name and has
                   10204: values that are the resource value.  I believe that the timestamps and
                   10205: versions are also returned.
                   10206: 
                   10207: 
1.243     albertel 10208: =back
                   10209: 
                   10210: =head2 Course Modification
                   10211: 
                   10212: =over 4
1.191     harris41 10213: 
                   10214: =item *
                   10215: 
1.243     albertel 10216: writecoursepref($courseid,%prefs) : write preferences (environment
                   10217: database) for a course
1.191     harris41 10218: 
                   10219: =item *
                   10220: 
1.1011    raeburn  10221: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10222: 
                   10223: =item *
                   10224: 
1.1038  ! raeburn  10225: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10226: 
                   10227: =back
                   10228: 
                   10229: =head2 Resource Subroutines
                   10230: 
                   10231: =over 4
1.191     harris41 10232: 
                   10233: =item *
                   10234: 
1.243     albertel 10235: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10236: 
                   10237: =item *
                   10238: 
1.243     albertel 10239: repcopy($filename) : subscribes to the requested file, and attempts to
                   10240: replicate from the owning library server, Might return
1.607     raeburn  10241: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10242: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10243: resource. Expects the local filesystem pathname
                   10244: (/home/httpd/html/res/....)
                   10245: 
                   10246: =back
                   10247: 
                   10248: =head2 Resource Information
                   10249: 
                   10250: =over 4
1.191     harris41 10251: 
                   10252: =item *
                   10253: 
1.243     albertel 10254: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10255: a vairety of different possible values, $varname should be a request
                   10256: string, and the other parameters can be used to specify who and what
                   10257: one is asking about.
                   10258: 
                   10259: Possible values for $varname are environment.lastname (or other item
                   10260: from the envirnment hash), user.name (or someother aspect about the
                   10261: user), resource.0.maxtries (or some other part and parameter of a
                   10262: resource)
1.204     albertel 10263: 
                   10264: =item *
                   10265: 
1.243     albertel 10266: directcondval($number) : get current value of a condition; reads from a state
                   10267: string
1.204     albertel 10268: 
                   10269: =item *
                   10270: 
1.243     albertel 10271: condval($condidx) : value of condition index based on state
1.204     albertel 10272: 
                   10273: =item *
                   10274: 
1.243     albertel 10275: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10276: resource's metadata, $what should be either a specific key, or either
                   10277: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10278: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10279: 
                   10280: this function automatically caches all requests
1.191     harris41 10281: 
                   10282: =item *
                   10283: 
1.243     albertel 10284: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10285: network of library servers; returns file handle of where SQL and regex results
                   10286: will be stored for query
1.191     harris41 10287: 
                   10288: =item *
                   10289: 
1.243     albertel 10290: symbread($filename) : return symbolic list entry (filename argument optional);
                   10291: returns the data handle
1.191     harris41 10292: 
                   10293: =item *
                   10294: 
1.243     albertel 10295: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10296: a possible symb for the URL in $thisfn, and if is an encryypted
                   10297: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10298: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10299: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10300: 
1.191     harris41 10301: 
                   10302: =item *
                   10303: 
1.243     albertel 10304: symbclean($symb) : removes versions numbers from a symb, returns the
                   10305: cleaned symb
1.191     harris41 10306: 
                   10307: =item *
                   10308: 
1.243     albertel 10309: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10310: course map, user must be in a course for it to work.
1.191     harris41 10311: 
                   10312: =item *
                   10313: 
1.243     albertel 10314: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10315: 
                   10316: =item *
                   10317: 
1.243     albertel 10318: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10319: a random seed, all arguments are optional, if they aren't sent it uses the
                   10320: environment to derive them. Note: if symb isn't sent and it can't get one
                   10321: from &symbread it will use the current time as its return value
1.191     harris41 10322: 
                   10323: =item *
                   10324: 
1.243     albertel 10325: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10326: unfakeable, receipt
1.191     harris41 10327: 
                   10328: =item *
                   10329: 
1.620     albertel 10330: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10331: 
                   10332: =item *
                   10333: 
1.243     albertel 10334: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10335: 
                   10336: =item *
                   10337: 
1.243     albertel 10338: 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 10339: 
                   10340: =item *
                   10341: 
1.243     albertel 10342: 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 10343: 
                   10344: =item *
                   10345: 
1.243     albertel 10346: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10347: 
                   10348: =item *
                   10349: 
1.243     albertel 10350: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10351: forcing spreadsheet to reevaluate the resource scores next time.
                   10352: 
                   10353: =back
                   10354: 
                   10355: =head2 Storing/Retreiving Data
                   10356: 
                   10357: =over 4
1.191     harris41 10358: 
                   10359: =item *
                   10360: 
1.243     albertel 10361: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10362: for this url; hashref needs to be given and should be a \%hashname; the
                   10363: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10364: be derived from the env
1.191     harris41 10365: 
                   10366: =item *
                   10367: 
1.243     albertel 10368: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10369: uses critical subroutine
1.191     harris41 10370: 
                   10371: =item *
                   10372: 
1.243     albertel 10373: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10374: all args are optional
1.191     harris41 10375: 
                   10376: =item *
                   10377: 
1.717     albertel 10378: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10379: dumps the complete (or key matching regexp) namespace into a hash
                   10380: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10381: normally &store()ed into
                   10382: 
                   10383: $range should be either an integer '100' (give me the first 100
                   10384:                                            matching records)
                   10385:               or be  two integers sperated by a - with no spaces
                   10386:                  '30-50' (give me the 30th through the 50th matching
                   10387:                           records)
                   10388: 
                   10389: 
                   10390: =item *
                   10391: 
                   10392: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10393: replaces a &store() version of data with a replacement set of data
                   10394: for a particular resource in a namespace passed in the $storehash hash 
                   10395: reference
                   10396: 
                   10397: =item *
                   10398: 
1.243     albertel 10399: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10400: works very similar to store/cstore, but all data is stored in a
                   10401: temporary location and can be reset using tmpreset, $storehash should
                   10402: be a hash reference, returns nothing on success
1.191     harris41 10403: 
                   10404: =item *
                   10405: 
1.243     albertel 10406: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10407: similar to restore, but all data is stored in a temporary location and
                   10408: can be reset using tmpreset. Returns a hash of values on success,
                   10409: error string otherwise.
1.191     harris41 10410: 
                   10411: =item *
                   10412: 
1.243     albertel 10413: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10414: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10415: 
                   10416: =item *
                   10417: 
1.243     albertel 10418: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10419: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10420: 
                   10421: =item *
                   10422: 
1.243     albertel 10423: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10424: namesp ($udom and $uname are optional)
1.191     harris41 10425: 
                   10426: =item *
                   10427: 
1.702     albertel 10428: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10429: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10430: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10431: 
1.702     albertel 10432: $range should be either an integer '100' (give me the first 100
                   10433:                                            matching records)
                   10434:               or be  two integers sperated by a - with no spaces
                   10435:                  '30-50' (give me the 30th through the 50th matching
                   10436:                           records)
1.449     matthew  10437: =item *
                   10438: 
                   10439: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10440: $store can be a scalar, an array reference, or if the amount to be 
                   10441: incremented is > 1, a hash reference.
                   10442: 
                   10443: ($udom and $uname are optional)
1.191     harris41 10444: 
                   10445: =item *
                   10446: 
1.243     albertel 10447: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10448: ($udom and $uname are optional)
1.191     harris41 10449: 
                   10450: =item *
                   10451: 
1.243     albertel 10452: cput($namespace,$storehash,$udom,$uname) : critical put
                   10453: ($udom and $uname are optional)
1.191     harris41 10454: 
                   10455: =item *
                   10456: 
1.748     albertel 10457: newput($namespace,$storehash,$udom,$uname) :
                   10458: 
                   10459: Attempts to store the items in the $storehash, but only if they don't
                   10460: currently exist, if this succeeds you can be certain that you have 
                   10461: successfully created a new key value pair in the $namespace db.
                   10462: 
                   10463: 
                   10464: Args:
                   10465:  $namespace: name of database to store values to
                   10466:  $storehash: hashref to store to the db
                   10467:  $udom: (optional) domain of user containing the db
                   10468:  $uname: (optional) name of user caontaining the db
                   10469: 
                   10470: Returns:
                   10471:  'ok' -> succeeded in storing all keys of $storehash
                   10472:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10473:                         least <key> already existed in the db (other
                   10474:                         requested keys may also already exist)
1.967     bisitz   10475:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10476:  'con_lost' -> unable to contact request server
                   10477:  'refused' -> action was not allowed by remote machine
                   10478: 
                   10479: 
                   10480: =item *
                   10481: 
1.243     albertel 10482: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10483: reference filled in from namesp (encrypts the return communication)
                   10484: ($udom and $uname are optional)
1.191     harris41 10485: 
                   10486: =item *
                   10487: 
1.243     albertel 10488: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10489: critical subroutine
                   10490: 
1.806     raeburn  10491: =item *
                   10492: 
1.860     raeburn  10493: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10494: array reference filled in from namespace found in domain level on either
                   10495: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10496: 
                   10497: =item *
                   10498: 
1.860     raeburn  10499: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10500: domain level either on specified domain server ($uhome) or primary domain 
                   10501: server ($udom and $uhome are optional)
1.806     raeburn  10502: 
1.943     raeburn  10503: =item * 
                   10504: 
                   10505: get_domain_defaults($target_domain) : returns hash with defaults for
                   10506: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10507: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10508: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10509: Values are retrieved from cache (if current), or from domain's configuration.db
                   10510: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10511: or lonTabs/domain.tab. 
                   10512: 
                   10513: %domdefaults = &get_auth_defaults($target_domain);
                   10514: 
1.243     albertel 10515: =back
                   10516: 
                   10517: =head2 Network Status Functions
                   10518: 
                   10519: =over 4
1.191     harris41 10520: 
                   10521: =item *
                   10522: 
                   10523: dirlist($uri) : return directory list based on URI
                   10524: 
                   10525: =item *
                   10526: 
1.243     albertel 10527: spareserver() : find server with least workload from spare.tab
                   10528: 
1.986     foxr     10529: 
                   10530: =item *
                   10531: 
                   10532: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10533: if there is no corresponding loncapa host.
                   10534: 
1.243     albertel 10535: =back
                   10536: 
1.986     foxr     10537: 
1.243     albertel 10538: =head2 Apache Request
                   10539: 
                   10540: =over 4
1.191     harris41 10541: 
                   10542: =item *
                   10543: 
1.243     albertel 10544: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10545: localhost, posts hash
                   10546: 
                   10547: =back
                   10548: 
                   10549: =head2 Data to String to Data
                   10550: 
                   10551: =over 4
1.191     harris41 10552: 
                   10553: =item *
                   10554: 
1.243     albertel 10555: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10556: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10557: 
                   10558: =item *
                   10559: 
1.243     albertel 10560: hashref2str($hashref) : convert a hashref into a string complete with
                   10561: escaping and '=' and '&' separators, supports elements that are
                   10562: arrayrefs and hashrefs
1.191     harris41 10563: 
                   10564: =item *
                   10565: 
1.243     albertel 10566: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10567: with escaping and '&' separators, supports elements that are arrayrefs
                   10568: and hashrefs
1.191     harris41 10569: 
                   10570: =item *
                   10571: 
1.243     albertel 10572: str2hash($string) : convert string to hash using unescaping and
                   10573: splitting on '=' and '&', supports elements that are arrayrefs and
                   10574: hashrefs
1.191     harris41 10575: 
                   10576: =item *
                   10577: 
1.243     albertel 10578: str2array($string) : convert string to hash using unescaping and
                   10579: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10580: 
                   10581: =back
                   10582: 
                   10583: =head2 Logging Routines
                   10584: 
                   10585: =over 4
                   10586: 
                   10587: These routines allow one to make log messages in the lonnet.log and
                   10588: lonnet.perm logfiles.
1.191     harris41 10589: 
                   10590: =item *
                   10591: 
1.243     albertel 10592: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10593: 
                   10594: =item *
                   10595: 
1.243     albertel 10596: logthis() : append message to the normal lonnet.log file, it gets
                   10597: preiodically rolled over and deleted.
1.191     harris41 10598: 
                   10599: =item *
                   10600: 
1.243     albertel 10601: logperm() : append a permanent message to lonnet.perm.log, this log
                   10602: file never gets deleted by any automated portion of the system, only
                   10603: messages of critical importance should go in here.
                   10604: 
                   10605: =back
                   10606: 
                   10607: =head2 General File Helper Routines
                   10608: 
                   10609: =over 4
1.191     harris41 10610: 
                   10611: =item *
                   10612: 
1.481     raeburn  10613: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10614: (a) files in /uploaded
                   10615:   (i) If a local copy of the file exists - 
                   10616:       compares modification date of local copy with last-modified date for 
                   10617:       definitive version stored on home server for course. If local copy is 
                   10618:       stale, requests a new version from the home server and stores it. 
                   10619:       If the original has been removed from the home server, then local copy 
                   10620:       is unlinked.
                   10621:   (ii) If local copy does not exist -
                   10622:       requests the file from the home server and stores it. 
                   10623:   
                   10624:   If $caller is 'uploadrep':  
                   10625:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10626:     for request for files originally uploaded via DOCS. 
                   10627:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10628:   
                   10629:   Otherwise:
                   10630:      This indicates a call from the content generation phase of the request.
                   10631:      -  returns the entire contents of the file or -1.
                   10632:      
                   10633: (b) files in /res
                   10634:    - returns the entire contents of a file or -1; 
                   10635:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10636: 
1.712     albertel 10637: 
                   10638: =item *
                   10639: 
                   10640: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10641:                   reference
                   10642: 
                   10643: returns either a stat() list of data about the file or an empty list
                   10644: if the file doesn't exist or couldn't find out about it (connection
                   10645: problems or user unknown)
                   10646: 
1.191     harris41 10647: =item *
                   10648: 
1.243     albertel 10649: filelocation($dir,$file) : returns file system location of a file
                   10650: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10651: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10652: and a file of ../bob will become /a/bob)
1.191     harris41 10653: 
                   10654: =item *
                   10655: 
                   10656: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10657: filelocation except for hrefs
                   10658: 
                   10659: =item *
                   10660: 
                   10661: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10662: 
1.243     albertel 10663: =back
                   10664: 
1.608     albertel 10665: =head2 Usererfile file routines (/uploaded*)
                   10666: 
                   10667: =over 4
                   10668: 
                   10669: =item *
                   10670: 
                   10671: userfileupload(): main rotine for putting a file in a user or course's
                   10672:                   filespace, arguments are,
                   10673: 
1.620     albertel 10674:  formname - required - this is the name of the element in $env where the
1.608     albertel 10675:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10676:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10677:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10678:  coursedoc - if true, store the file in the course of the active role
                   10679:              of the current user
                   10680:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10681:          if undefined, it will be placed in "unknown"
                   10682: 
                   10683:  (This routine calls clean_filename() to remove any dangerous
                   10684:  characters from the filename, and then calls finuserfileupload() to
                   10685:  complete the transaction)
                   10686: 
                   10687:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10688:  and /adm/notfound.html if unsuccessful
                   10689: 
                   10690: =item *
                   10691: 
                   10692: clean_filename(): routine for cleaing a filename up for storage in
                   10693:                  userfile space, argument is:
                   10694: 
                   10695:  filename - proposed filename
                   10696: 
                   10697: returns: the new clean filename
                   10698: 
                   10699: =item *
                   10700: 
                   10701: finishuserfileupload(): routine that creaes and sends the file to
                   10702: userspace, probably shouldn't be called directly
                   10703: 
                   10704:   docuname: username or courseid of destination for the file
                   10705:   docudom: domain of user/course of destination for the file
                   10706:   formname: same as for userfileupload()
                   10707:   fname: filename (inculding subdirectories) for the file
                   10708: 
                   10709:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10710:  and /adm/notfound.html if unsuccessful
                   10711: 
                   10712: =item *
                   10713: 
                   10714: renameuserfile(): renames an existing userfile to a new name
                   10715: 
                   10716:   Args:
                   10717:    docuname: username or courseid of destination for the file
                   10718:    docudom: domain of user/course of destination for the file
                   10719:    old: current file name (including any subdirs under userfiles)
                   10720:    new: desired file name (including any subdirs under userfiles)
                   10721: 
                   10722: =item *
                   10723: 
                   10724: mkdiruserfile(): creates a directory is a userfiles dir
                   10725: 
                   10726:   Args:
                   10727:    docuname: username or courseid of destination for the file
                   10728:    docudom: domain of user/course of destination for the file
                   10729:    dir: dir to create (including any subdirs under userfiles)
                   10730: 
                   10731: =item *
                   10732: 
                   10733: removeuserfile(): removes a file that exists in userfiles
                   10734: 
                   10735:   Args:
                   10736:    docuname: username or courseid of destination for the file
                   10737:    docudom: domain of user/course of destination for the file
                   10738:    fname: filname to delete (including any subdirs under userfiles)
                   10739: 
                   10740: =item *
                   10741: 
                   10742: removeuploadedurl(): convience function for removeuserfile()
                   10743: 
                   10744:   Args:
                   10745:    url:  a full /uploaded/... url to delete
                   10746: 
1.747     albertel 10747: =item * 
                   10748: 
                   10749: get_portfile_permissions():
                   10750:   Args:
                   10751:     domain: domain of user or course contain the portfolio files
                   10752:     user: name of user or num of course contain the portfolio files
                   10753:   Returns:
                   10754:     hashref of a dump of the proper file_permissions.db
                   10755:    
                   10756: 
                   10757: =item * 
                   10758: 
                   10759: get_access_controls():
                   10760: 
                   10761: Args:
                   10762:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10763:   group: (optional) the group you want the files associated with
                   10764:   file: (optional) the file you want access info on
                   10765: 
                   10766: Returns:
1.749     raeburn  10767:     a hash (keys are file names) of hashes containing
                   10768:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10769:         values are XML containing access control settings (see below) 
1.747     albertel 10770: 
                   10771: Internal notes:
                   10772: 
1.749     raeburn  10773:  access controls are stored in file_permissions.db as key=value pairs.
                   10774:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10775:         where scope -> public,guest,course,group,domains or users.
                   10776:               end -> UNIX time for end of access (0 -> no end date)
                   10777:               start -> UNIX time for start of access
                   10778: 
                   10779:     value -> XML description of access control
                   10780:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10781:             <start></start>
                   10782:             <end></end>
                   10783: 
                   10784:             <password></password>  for scope type = guest
                   10785: 
                   10786:             <domain></domain>     for scope type = course or group
                   10787:             <number></number>
                   10788:             <roles id="">
                   10789:              <role></role>
                   10790:              <access></access>
                   10791:              <section></section>
                   10792:              <group></group>
                   10793:             </roles>
                   10794: 
                   10795:             <dom></dom>         for scope type = domains
                   10796: 
                   10797:             <users>             for scope type = users
                   10798:              <user>
                   10799:               <uname></uname>
                   10800:               <udom></udom>
                   10801:              </user>
                   10802:             </users>
                   10803:            </scope> 
                   10804:               
                   10805:  Access data is also aggregated for each file in an additional key=value pair:
                   10806:  key -> path to file/file_name\0accesscontrol 
                   10807:  value -> reference to hash
                   10808:           hash contains key = value pairs
                   10809:           where key = uniqueID:scope_end_start
                   10810:                 value = UNIX time record was last updated
                   10811: 
                   10812:           Used to improve speed of look-ups of access controls for each file.  
                   10813:  
                   10814:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10815: 
                   10816: modify_access_controls():
                   10817: 
                   10818: Modifies access controls for a portfolio file
                   10819: Args
                   10820: 1. file name
                   10821: 2. reference to hash of required changes,
                   10822: 3. domain
                   10823: 4. username
                   10824:   where domain,username are the domain of the portfolio owner 
                   10825:   (either a user or a course) 
                   10826: 
                   10827: Returns:
                   10828: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10829: 2. result of deletions ('ok' or 'error', with error message).
                   10830: 3. reference to hash of any new or updated access controls.
                   10831: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10832:    key = integer (inbound ID)
                   10833:    value = uniqueID  
1.747     albertel 10834: 
1.608     albertel 10835: =back
                   10836: 
1.243     albertel 10837: =head2 HTTP Helper Routines
                   10838: 
                   10839: =over 4
                   10840: 
1.191     harris41 10841: =item *
                   10842: 
                   10843: escape() : unpack non-word characters into CGI-compatible hex codes
                   10844: 
                   10845: =item *
                   10846: 
                   10847: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10848: 
1.243     albertel 10849: =back
                   10850: 
                   10851: =head1 PRIVATE SUBROUTINES
                   10852: 
                   10853: =head2 Underlying communication routines (Shouldn't call)
                   10854: 
                   10855: =over 4
                   10856: 
                   10857: =item *
                   10858: 
                   10859: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10860: 
                   10861: =item *
                   10862: 
                   10863: reply() : uses subreply to send a message to remote machine, logs all failures
                   10864: 
                   10865: =item *
                   10866: 
                   10867: critical() : passes a critical message to another server; if cannot
                   10868: get through then place message in connection buffer directory and
                   10869: returns con_delayed, if incapable of saving message, returns
                   10870: con_failed
                   10871: 
                   10872: =item *
                   10873: 
                   10874: reconlonc() : tries to reconnect lonc client processes.
                   10875: 
                   10876: =back
                   10877: 
                   10878: =head2 Resource Access Logging
                   10879: 
                   10880: =over 4
                   10881: 
                   10882: =item *
                   10883: 
                   10884: flushcourselogs() : flush (save) buffer logs and access logs
                   10885: 
                   10886: =item *
                   10887: 
                   10888: courselog($what) : save message for course in hash
                   10889: 
                   10890: =item *
                   10891: 
                   10892: courseacclog($what) : save message for course using &courselog().  Perform
                   10893: special processing for specific resource types (problems, exams, quizzes, etc).
                   10894: 
1.191     harris41 10895: =item *
                   10896: 
                   10897: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10898: as a PerlChildExitHandler
1.243     albertel 10899: 
                   10900: =back
                   10901: 
                   10902: =head2 Other
                   10903: 
                   10904: =over 4
                   10905: 
                   10906: =item *
                   10907: 
                   10908: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10909: 
                   10910: =back
                   10911: 
                   10912: =cut
1.877     foxr     10913: 

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