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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1025  ! raeburn     4: # $Id: lonnet.pm,v 1.1024 2009/08/28 19:43:10 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.799     raeburn   788:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   789: 		       $server);
                    790:     if (! $answer) {
                    791: 	&logthis("No reply on password change request to $server ".
                    792: 		 "by $uname in domain $udom.");
                    793:     } elsif ($answer =~ "^ok") {
                    794:         &logthis("$uname in $udom successfully changed their password ".
                    795: 		 "on $server.");
                    796:     } elsif ($answer =~ "^pwchange_failure") {
                    797: 	&logthis("$uname in $udom was unable to change their password ".
                    798: 		 "on $server.  The action was blocked by either lcpasswd ".
                    799: 		 "or pwchange");
                    800:     } elsif ($answer =~ "^non_authorized") {
                    801:         &logthis("$uname in $udom did not get their password correct when ".
                    802: 		 "attempting to change it on $server.");
                    803:     } elsif ($answer =~ "^auth_mode_error") {
                    804:         &logthis("$uname in $udom attempted to change their password despite ".
                    805: 		 "not being locally or internally authenticated on $server.");
                    806:     } elsif ($answer =~ "^unknown_user") {
                    807:         &logthis("$uname in $udom attempted to change their password ".
                    808: 		 "on $server but were unable to because $server is not ".
                    809: 		 "their home server.");
                    810:     } elsif ($answer =~ "^refused") {
                    811: 	&logthis("$server refused to change $uname in $udom password because ".
                    812: 		 "it was sent an unencrypted request to change the password.");
                    813:     }
                    814:     return $answer;
1.1       albertel  815: }
                    816: 
1.169     harris41  817: # ----------------------- Try to determine user's current authentication scheme
                    818: 
                    819: sub queryauthenticate {
                    820:     my ($uname,$udom)=@_;
1.456     albertel  821:     my $uhome=&homeserver($uname,$udom);
                    822:     if (!$uhome) {
                    823: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    824: 	return 'no_host';
                    825:     }
                    826:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    827:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    828: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  829:     }
1.456     albertel  830:     return $answer;
1.169     harris41  831: }
                    832: 
1.1       albertel  833: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       834: 
1.1       albertel  835: sub authenticate {
1.952     raeburn   836:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  837:     $upass=&escape($upass);
                    838:     $uname= &LONCAPA::clean_username($uname);
1.836     www       839:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   840:     my $newhome;
1.836     www       841:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    842: # Maybe the machine was offline and only re-appeared again recently?
                    843:         &reconlonc();
                    844: # One more
1.952     raeburn   845: 	$uhome=&homeserver($uname,$udom,1);
                    846:         if (($uhome eq 'no_host') && $checkdefauth) {
                    847:             if (defined(&domain($udom,'primary'))) {
                    848:                 $newhome=&domain($udom,'primary');
                    849:             }
                    850:             if ($newhome ne '') {
                    851:                 $uhome = $newhome;
                    852:             }
                    853:         }
1.836     www       854: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    855: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   856: 	    return 'no_host';
                    857:         }
1.1       albertel  858:     }
1.952     raeburn   859:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  860:     if ($answer eq 'authorized') {
1.952     raeburn   861:         if ($newhome) {
                    862:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    863:             return 'no_account_on_host'; 
                    864:         } else {
                    865:             &logthis("User $uname at $udom authorized by $uhome");
                    866:             return $uhome;
                    867:         }
1.471     albertel  868:     }
                    869:     if ($answer eq 'non_authorized') {
                    870: 	&logthis("User $uname at $udom rejected by $uhome");
                    871: 	return 'no_host'; 
1.9       www       872:     }
1.471     albertel  873:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  874:     return 'no_host';
                    875: }
                    876: 
                    877: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       878: 
1.599     albertel  879: my %homecache;
1.1       albertel  880: sub homeserver {
1.230     stredwic  881:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  882:     my $index="$uname:$udom";
1.426     albertel  883: 
1.599     albertel  884:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  885: 
                    886:     my %servers = &get_servers($udom,'library');
                    887:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  888:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  889: 		 exists($badServerCache{$tryserver}));
1.841     albertel  890: 
                    891: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    892: 	if ($answer eq 'found') {
                    893: 	    delete($badServerCache{$tryserver}); 
                    894: 	    return $homecache{$index}=$tryserver;
                    895: 	} elsif ($answer eq 'no_host') {
                    896: 	    $badServerCache{$tryserver}=1;
                    897: 	}
1.1       albertel  898:     }    
                    899:     return 'no_host';
1.70      www       900: }
                    901: 
                    902: # ------------------------------------- Find the usernames behind a list of IDs
                    903: 
                    904: sub idget {
                    905:     my ($udom,@ids)=@_;
                    906:     my %returnhash=();
                    907:     
1.841     albertel  908:     my %servers = &get_servers($udom,'library');
                    909:     foreach my $tryserver (keys(%servers)) {
                    910: 	my $idlist=join('&',@ids);
                    911: 	$idlist=~tr/A-Z/a-z/; 
                    912: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    913: 	my @answer=();
                    914: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    915: 	    @answer=split(/\&/,$reply);
                    916: 	}                    ;
                    917: 	my $i;
                    918: 	for ($i=0;$i<=$#ids;$i++) {
                    919: 	    if ($answer[$i]) {
                    920: 		$returnhash{$ids[$i]}=$answer[$i];
                    921: 	    } 
                    922: 	}
                    923:     } 
1.70      www       924:     return %returnhash;
                    925: }
                    926: 
                    927: # ------------------------------------- Find the IDs behind a list of usernames
                    928: 
                    929: sub idrget {
                    930:     my ($udom,@unames)=@_;
                    931:     my %returnhash=();
1.800     albertel  932:     foreach my $uname (@unames) {
                    933:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  934:     }
1.70      www       935:     return %returnhash;
                    936: }
                    937: 
                    938: # ------------------------------- Store away a list of names and associated IDs
                    939: 
                    940: sub idput {
                    941:     my ($udom,%ids)=@_;
                    942:     my %servers=();
1.800     albertel  943:     foreach my $uname (keys(%ids)) {
                    944: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    945:         my $uhom=&homeserver($uname,$udom);
1.70      www       946:         if ($uhom ne 'no_host') {
1.800     albertel  947:             my $id=&escape($ids{$uname});
1.70      www       948:             $id=~tr/A-Z/a-z/;
1.800     albertel  949:             my $esc_unam=&escape($uname);
1.70      www       950: 	    if ($servers{$uhom}) {
1.800     albertel  951: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       952:             } else {
1.800     albertel  953:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       954:             }
                    955:         }
1.191     harris41  956:     }
1.800     albertel  957:     foreach my $server (keys(%servers)) {
                    958:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  959:     }
1.344     www       960: }
                    961: 
1.1023    raeburn   962: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn   963: sub dump_dom {
1.1023    raeburn   964:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn   965:     if (!$udom) {
                    966:         $udom=$env{'user.domain'};
                    967:     }
                    968:     my %returnhash;
1.1023    raeburn   969:     if ($udom) {
                    970:         my $uname = &get_domainconfiguser($udom);
                    971:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn   972:     }
                    973:     return %returnhash;
                    974: }
                    975: 
1.1023    raeburn   976: # ------------------------------------------ get items from domain db files   
1.806     raeburn   977: 
                    978: sub get_dom {
1.860     raeburn   979:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   980:     my $items='';
                    981:     foreach my $item (@$storearr) {
                    982:         $items.=&escape($item).'&';
                    983:     }
                    984:     $items=~s/\&$//;
1.860     raeburn   985:     if (!$udom) {
                    986:         $udom=$env{'user.domain'};
                    987:         if (defined(&domain($udom,'primary'))) {
                    988:             $uhome=&domain($udom,'primary');
                    989:         } else {
1.874     albertel  990:             undef($uhome);
1.860     raeburn   991:         }
                    992:     } else {
                    993:         if (!$uhome) {
                    994:             if (defined(&domain($udom,'primary'))) {
                    995:                 $uhome=&domain($udom,'primary');
                    996:             }
                    997:         }
                    998:     }
                    999:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1000:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1001:         my %returnhash;
1.875     albertel 1002:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1003:             return %returnhash;
                   1004:         }
1.806     raeburn  1005:         my @pairs=split(/\&/,$rep);
                   1006:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1007:             return @pairs;
                   1008:         }
                   1009:         my $i=0;
                   1010:         foreach my $item (@$storearr) {
                   1011:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1012:             $i++;
                   1013:         }
                   1014:         return %returnhash;
                   1015:     } else {
1.880     banghart 1016:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1017:     }
                   1018: }
                   1019: 
                   1020: # -------------------------------------------- put items in domain db files 
                   1021: 
                   1022: sub put_dom {
1.860     raeburn  1023:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1024:     if (!$udom) {
                   1025:         $udom=$env{'user.domain'};
                   1026:         if (defined(&domain($udom,'primary'))) {
                   1027:             $uhome=&domain($udom,'primary');
                   1028:         } else {
1.874     albertel 1029:             undef($uhome);
1.860     raeburn  1030:         }
                   1031:     } else {
                   1032:         if (!$uhome) {
                   1033:             if (defined(&domain($udom,'primary'))) {
                   1034:                 $uhome=&domain($udom,'primary');
                   1035:             }
                   1036:         }
                   1037:     } 
                   1038:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1039:         my $items='';
                   1040:         foreach my $item (keys(%$storehash)) {
                   1041:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1042:         }
                   1043:         $items=~s/\&$//;
                   1044:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1045:     } else {
1.860     raeburn  1046:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1047:     }
                   1048: }
                   1049: 
1.1023    raeburn  1050: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1051: sub newput_dom {
1.1023    raeburn  1052:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1053:     my $result;
                   1054:     if (!$udom) {
                   1055:         $udom=$env{'user.domain'};
                   1056:     }
1.1023    raeburn  1057:     if ($udom) {
                   1058:         my $uname = &get_domainconfiguser($udom);
                   1059:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1060:     }
                   1061:     return $result;
                   1062: }
                   1063: 
1.1023    raeburn  1064: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1065: sub del_dom {
1.1023    raeburn  1066:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1067:     if (ref($storearr) eq 'ARRAY') {
                   1068:         if (!$udom) {
                   1069:             $udom=$env{'user.domain'};
                   1070:         }
1.1023    raeburn  1071:         if ($udom) {
                   1072:             my $uname = &get_domainconfiguser($udom); 
                   1073:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1074:         }
                   1075:     }
                   1076: }
                   1077: 
1.1023    raeburn  1078: # ----------------------------------construct domainconfig user for a domain 
                   1079: sub get_domainconfiguser {
                   1080:     my ($udom) = @_;
                   1081:     return $udom.'-domainconfig';
                   1082: }
                   1083: 
1.837     raeburn  1084: sub retrieve_inst_usertypes {
                   1085:     my ($udom) = @_;
                   1086:     my (%returnhash,@order);
1.989     raeburn  1087:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1088:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1089:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1090:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1091:         @order = @{$domdefs{'inststatusorder'}};
                   1092:     } else {
                   1093:         if (defined(&domain($udom,'primary'))) {
                   1094:             my $uhome=&domain($udom,'primary');
                   1095:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1096:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1097:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1098:                 return (\%returnhash,\@order);
                   1099:             }
                   1100:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1101:             my @pairs=split(/\&/,$hashitems);
                   1102:             foreach my $item (@pairs) {
                   1103:                 my ($key,$value)=split(/=/,$item,2);
                   1104:                 $key = &unescape($key);
                   1105:                 next if ($key =~ /^error: 2 /);
                   1106:                 $returnhash{$key}=&thaw_unescape($value);
                   1107:             }
                   1108:             my @esc_order = split(/\&/,$orderitems);
                   1109:             foreach my $item (@esc_order) {
                   1110:                 push(@order,&unescape($item));
                   1111:             }
                   1112:         } else {
                   1113:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1114:         }
                   1115:     }
                   1116:     return (\%returnhash,\@order);
                   1117: }
                   1118: 
1.868     raeburn  1119: sub is_domainimage {
                   1120:     my ($url) = @_;
                   1121:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1122:         if (&domain($1) ne '') {
                   1123:             return '1';
                   1124:         }
                   1125:     }
                   1126:     return;
                   1127: }
                   1128: 
1.899     raeburn  1129: sub inst_directory_query {
                   1130:     my ($srch) = @_;
                   1131:     my $udom = $srch->{'srchdomain'};
                   1132:     my %results;
                   1133:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1134:     my $outcome;
1.899     raeburn  1135:     if ($homeserver ne '') {
1.904     albertel 1136: 	my $queryid=&reply("querysend:instdirsearch:".
                   1137: 			   &escape($srch->{'srchby'}).':'.
                   1138: 			   &escape($srch->{'srchterm'}).':'.
                   1139: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1140: 	my $host=&hostname($homeserver);
                   1141: 	if ($queryid !~/^\Q$host\E\_/) {
                   1142: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1143: 	    return;
                   1144: 	}
                   1145: 	my $response = &get_query_reply($queryid);
                   1146: 	my $maxtries = 5;
                   1147: 	my $tries = 1;
                   1148: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1149: 	    $response = &get_query_reply($queryid);
                   1150: 	    $tries ++;
                   1151: 	}
                   1152: 
                   1153:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1154:             if ($response eq 'unavailable') {
                   1155:                 $outcome = $response;
                   1156:             } else {
                   1157:                 $outcome = 'ok';
                   1158:                 my @matches = split(/\n/,$response);
                   1159:                 foreach my $match (@matches) {
                   1160:                     my ($key,$value) = split(/=/,$match);
                   1161:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1162:                 }
1.899     raeburn  1163:             }
                   1164:         }
                   1165:     }
1.909     raeburn  1166:     return ($outcome,%results);
1.899     raeburn  1167: }
                   1168: 
                   1169: sub usersearch {
                   1170:     my ($srch) = @_;
                   1171:     my $dom = $srch->{'srchdomain'};
                   1172:     my %results;
                   1173:     my %libserv = &all_library();
                   1174:     my $query = 'usersearch';
                   1175:     foreach my $tryserver (keys(%libserv)) {
                   1176:         if (&host_domain($tryserver) eq $dom) {
                   1177:             my $host=&hostname($tryserver);
                   1178:             my $queryid=
1.911     raeburn  1179:                 &reply("querysend:".&escape($query).':'.
                   1180:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1181:                        &escape($srch->{'srchtype'}).':'.
                   1182:                        &escape($srch->{'srchterm'}),$tryserver);
                   1183:             if ($queryid !~/^\Q$host\E\_/) {
                   1184:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1185:                 next;
1.899     raeburn  1186:             }
                   1187:             my $reply = &get_query_reply($queryid);
                   1188:             my $maxtries = 1;
                   1189:             my $tries = 1;
                   1190:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1191:                 $reply = &get_query_reply($queryid);
                   1192:                 $tries ++;
                   1193:             }
                   1194:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1195:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1196:             } else {
1.911     raeburn  1197:                 my @matches;
                   1198:                 if ($reply =~ /\n/) {
                   1199:                     @matches = split(/\n/,$reply);
                   1200:                 } else {
                   1201:                     @matches = split(/\&/,$reply);
                   1202:                 }
1.899     raeburn  1203:                 foreach my $match (@matches) {
                   1204:                     my ($uname,$udom,%userhash);
1.911     raeburn  1205:                     foreach my $entry (split(/:/,$match)) {
                   1206:                         my ($key,$value) =
                   1207:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1208:                         $userhash{$key} = $value;
                   1209:                         if ($key eq 'username') {
                   1210:                             $uname = $value;
                   1211:                         } elsif ($key eq 'domain') {
                   1212:                             $udom = $value;
1.911     raeburn  1213:                         }
1.899     raeburn  1214:                     }
                   1215:                     $results{$uname.':'.$udom} = \%userhash;
                   1216:                 }
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     return %results;
                   1221: }
                   1222: 
1.912     raeburn  1223: sub get_instuser {
                   1224:     my ($udom,$uname,$id) = @_;
                   1225:     my $homeserver = &domain($udom,'primary');
                   1226:     my ($outcome,%results);
                   1227:     if ($homeserver ne '') {
                   1228:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1229:                            &escape($id).':'.&escape($udom),$homeserver);
                   1230:         my $host=&hostname($homeserver);
                   1231:         if ($queryid !~/^\Q$host\E\_/) {
                   1232:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1233:             return;
                   1234:         }
                   1235:         my $response = &get_query_reply($queryid);
                   1236:         my $maxtries = 5;
                   1237:         my $tries = 1;
                   1238:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1239:             $response = &get_query_reply($queryid);
                   1240:             $tries ++;
                   1241:         }
                   1242:         if (!&error($response) && $response ne 'refused') {
                   1243:             if ($response eq 'unavailable') {
                   1244:                 $outcome = $response;
                   1245:             } else {
                   1246:                 $outcome = 'ok';
                   1247:                 my @matches = split(/\n/,$response);
                   1248:                 foreach my $match (@matches) {
                   1249:                     my ($key,$value) = split(/=/,$match);
                   1250:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1251:                 }
                   1252:             }
                   1253:         }
                   1254:     }
                   1255:     my %userinfo;
                   1256:     if (ref($results{$uname}) eq 'HASH') {
                   1257:         %userinfo = %{$results{$uname}};
                   1258:     } 
                   1259:     return ($outcome,%userinfo);
                   1260: }
                   1261: 
                   1262: sub inst_rulecheck {
1.923     raeburn  1263:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1264:     my %returnhash;
                   1265:     if ($udom ne '') {
                   1266:         if (ref($rules) eq 'ARRAY') {
                   1267:             @{$rules} = map {&escape($_);} (@{$rules});
                   1268:             my $rulestr = join(':',@{$rules});
                   1269:             my $homeserver=&domain($udom,'primary');
                   1270:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1271:                 my $response;
                   1272:                 if ($item eq 'username') {                
                   1273:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1274:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1275:                                               $homeserver));
1.923     raeburn  1276:                 } elsif ($item eq 'id') {
                   1277:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1278:                                               ':'.&escape($id).':'.$rulestr,
                   1279:                                               $homeserver));
1.945     raeburn  1280:                 } elsif ($item eq 'selfcreate') {
                   1281:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1282:                                                &escape($udom).':'.&escape($uname).
                   1283:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1284:                 }
1.912     raeburn  1285:                 if ($response ne 'refused') {
                   1286:                     my @pairs=split(/\&/,$response);
                   1287:                     foreach my $item (@pairs) {
                   1288:                         my ($key,$value)=split(/=/,$item,2);
                   1289:                         $key = &unescape($key);
                   1290:                         next if ($key =~ /^error: 2 /);
                   1291:                         $returnhash{$key}=&thaw_unescape($value);
                   1292:                     }
                   1293:                 }
                   1294:             }
                   1295:         }
                   1296:     }
                   1297:     return %returnhash;
                   1298: }
                   1299: 
                   1300: sub inst_userrules {
1.923     raeburn  1301:     my ($udom,$check) = @_;
1.912     raeburn  1302:     my (%ruleshash,@ruleorder);
                   1303:     if ($udom ne '') {
                   1304:         my $homeserver=&domain($udom,'primary');
                   1305:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1306:             my $response;
                   1307:             if ($check eq 'id') {
                   1308:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1309:                                  $homeserver);
1.943     raeburn  1310:             } elsif ($check eq 'email') {
                   1311:                 $response=&reply('instemailrules:'.&escape($udom),
                   1312:                                  $homeserver);
1.923     raeburn  1313:             } else {
                   1314:                 $response=&reply('instuserrules:'.&escape($udom),
                   1315:                                  $homeserver);
                   1316:             }
1.912     raeburn  1317:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1318:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1319:                 ($response ne 'no_such_host')) {
                   1320:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1321:                 my @pairs=split(/\&/,$hashitems);
                   1322:                 foreach my $item (@pairs) {
                   1323:                     my ($key,$value)=split(/=/,$item,2);
                   1324:                     $key = &unescape($key);
                   1325:                     next if ($key =~ /^error: 2 /);
                   1326:                     $ruleshash{$key}=&thaw_unescape($value);
                   1327:                 }
                   1328:                 my @esc_order = split(/\&/,$orderitems);
                   1329:                 foreach my $item (@esc_order) {
                   1330:                     push(@ruleorder,&unescape($item));
                   1331:                 }
                   1332:             }
                   1333:         }
                   1334:     }
                   1335:     return (\%ruleshash,\@ruleorder);
                   1336: }
                   1337: 
1.976     raeburn  1338: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1339: 
                   1340: sub get_domain_defaults {
                   1341:     my ($domain) = @_;
                   1342:     my $cachetime = 60*60*24;
                   1343:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1344:     if (defined($cached)) {
                   1345:         if (ref($result) eq 'HASH') {
                   1346:             return %{$result};
                   1347:         }
                   1348:     }
                   1349:     my %domdefaults;
                   1350:     my %domconfig =
1.989     raeburn  1351:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1352:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1353:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1354:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1355:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1356:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1357:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1358:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1359:     } else {
                   1360:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1361:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1362:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1363:     }
1.976     raeburn  1364:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1365:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1366:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1367:         } else {
                   1368:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1369:         } 
                   1370:         my @usertools = ('aboutme','blog','portfolio');
                   1371:         foreach my $item (@usertools) {
                   1372:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1373:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1374:             }
                   1375:         }
                   1376:     }
1.985     raeburn  1377:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1378:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1379:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1380:         }
                   1381:     }
1.989     raeburn  1382:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1383:         foreach my $item ('inststatustypes','inststatusorder') {
                   1384:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1385:         }
                   1386:     }
1.943     raeburn  1387:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1388:                                   $cachetime);
                   1389:     return %domdefaults;
                   1390: }
                   1391: 
1.344     www      1392: # --------------------------------------------------- Assign a key to a student
                   1393: 
                   1394: sub assign_access_key {
1.364     www      1395: #
                   1396: # a valid key looks like uname:udom#comments
                   1397: # comments are being appended
                   1398: #
1.498     www      1399:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1400:     $kdom=
1.620     albertel 1401:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1402:     $knum=
1.620     albertel 1403:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1404:     $cdom=
1.620     albertel 1405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1406:     $cnum=
1.620     albertel 1407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1408:     $udom=$env{'user.name'} unless (defined($udom));
                   1409:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1410:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1411:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1412:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1413:                                                   # assigned to this person
                   1414:                                                   # - this should not happen,
1.345     www      1415:                                                   # unless something went wrong
                   1416:                                                   # the first time around
                   1417: # ready to assign
1.364     www      1418:         $logentry=$1.'; '.$logentry;
1.496     www      1419:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1420:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1421: # key now belongs to user
1.346     www      1422: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1423:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1424:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1425:                 return 'ok';
                   1426:             } else {
                   1427:                 return 
                   1428:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1429: 	    }
                   1430:         } else {
                   1431:             return 'error: Could not assign key, try again later.';
                   1432:         }
1.364     www      1433:     } elsif (!$existing{$ckey}) {
1.345     www      1434: # the key does not exist
                   1435: 	return 'error: The key does not exist';
                   1436:     } else {
                   1437: # the key is somebody else's
                   1438: 	return 'error: The key is already in use';
                   1439:     }
1.344     www      1440: }
                   1441: 
1.364     www      1442: # ------------------------------------------ put an additional comment on a key
                   1443: 
                   1444: sub comment_access_key {
                   1445: #
                   1446: # a valid key looks like uname:udom#comments
                   1447: # comments are being appended
                   1448: #
                   1449:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1450:     $cdom=
1.620     albertel 1451:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1452:     $cnum=
1.620     albertel 1453:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1454:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1455:     if ($existing{$ckey}) {
                   1456:         $existing{$ckey}.='; '.$logentry;
                   1457: # ready to assign
1.367     www      1458:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1459:                                                  $cdom,$cnum) eq 'ok') {
                   1460: 	    return 'ok';
                   1461:         } else {
                   1462: 	    return 'error: Count not store comment.';
                   1463:         }
                   1464:     } else {
                   1465: # the key does not exist
                   1466: 	return 'error: The key does not exist';
                   1467:     }
                   1468: }
                   1469: 
1.344     www      1470: # ------------------------------------------------------ Generate a set of keys
                   1471: 
                   1472: sub generate_access_keys {
1.364     www      1473:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1474:     $cdom=
1.620     albertel 1475:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1476:     $cnum=
1.620     albertel 1477:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1478:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1479:     unless (($cdom) && ($cnum)) { return 0; }
                   1480:     if ($number>10000) { return 0; }
                   1481:     sleep(2); # make sure don't get same seed twice
                   1482:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1483:     my $total=0;
                   1484:     for (my $i=1;$i<=$number;$i++) {
                   1485:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1486:                   sprintf("%lx",int(100000*rand)).'-'.
                   1487:                   sprintf("%lx",int(100000*rand));
                   1488:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1489:        $newkey=~s/0/h/g; # and also 0 and O
                   1490:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1491:        if ($existing{$newkey}) {
                   1492:            $i--;
                   1493:        } else {
1.364     www      1494: 	  if (&put('accesskeys',
                   1495:               { $newkey => '# generated '.localtime().
1.620     albertel 1496:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1497:                            '; '.$logentry },
                   1498: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1499:               $total++;
                   1500: 	  }
                   1501:        }
                   1502:     }
1.620     albertel 1503:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1504:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1505:     return $total;
                   1506: }
                   1507: 
                   1508: # ------------------------------------------------------- Validate an accesskey
                   1509: 
                   1510: sub validate_access_key {
                   1511:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1512:     $cdom=
1.620     albertel 1513:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1514:     $cnum=
1.620     albertel 1515:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1516:     $udom=$env{'user.domain'} unless (defined($udom));
                   1517:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1518:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1519:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1520: }
                   1521: 
                   1522: # ------------------------------------- Find the section of student in a course
1.652     albertel 1523: sub devalidate_getsection_cache {
                   1524:     my ($udom,$unam,$courseid)=@_;
                   1525:     my $hashid="$udom:$unam:$courseid";
                   1526:     &devalidate_cache_new('getsection',$hashid);
                   1527: }
1.298     matthew  1528: 
1.815     albertel 1529: sub courseid_to_courseurl {
                   1530:     my ($courseid) = @_;
                   1531:     #already url style courseid
                   1532:     return $courseid if ($courseid =~ m{^/});
                   1533: 
                   1534:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1535: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1536: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1537: 	return "/$cdom/$cnum";
                   1538:     }
                   1539: 
                   1540:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1541:     if (exists($courseinfo{'num'})) {
                   1542: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1543:     }
                   1544: 
                   1545:     return undef;
                   1546: }
                   1547: 
1.298     matthew  1548: sub getsection {
                   1549:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1550:     my $cachetime=1800;
1.551     albertel 1551: 
                   1552:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1553:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1554:     if (defined($cached)) { return $result; }
                   1555: 
1.298     matthew  1556:     my %Pending; 
                   1557:     my %Expired;
                   1558:     #
                   1559:     # Each role can either have not started yet (pending), be active, 
                   1560:     #    or have expired.
                   1561:     #
                   1562:     # If there is an active role, we are done.
                   1563:     #
                   1564:     # If there is more than one role which has not started yet, 
                   1565:     #     choose the one which will start sooner
                   1566:     # If there is one role which has not started yet, return it.
                   1567:     #
                   1568:     # If there is more than one expired role, choose the one which ended last.
                   1569:     # If there is a role which has expired, return it.
                   1570:     #
1.815     albertel 1571:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1572:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1573:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1574:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1575:         my $section=$1;
                   1576:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1577:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1578:         my $now=time;
1.548     albertel 1579:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1580:             $Expired{$end}=$section;
                   1581:             next;
                   1582:         }
1.548     albertel 1583:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1584:             $Pending{$start}=$section;
                   1585:             next;
                   1586:         }
1.599     albertel 1587:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1588:     }
                   1589:     #
                   1590:     # Presumedly there will be few matching roles from the above
                   1591:     # loop and the sorting time will be negligible.
                   1592:     if (scalar(keys(%Pending))) {
                   1593:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1594:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1595:     } 
                   1596:     if (scalar(keys(%Expired))) {
                   1597:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1598:         my $time = pop(@sorted);
1.599     albertel 1599:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1600:     }
1.599     albertel 1601:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1602: }
1.70      www      1603: 
1.599     albertel 1604: sub save_cache {
                   1605:     &purge_remembered();
1.722     albertel 1606:     #&Apache::loncommon::validate_page();
1.620     albertel 1607:     undef(%env);
1.780     albertel 1608:     undef($env_loaded);
1.599     albertel 1609: }
1.452     albertel 1610: 
1.599     albertel 1611: my $to_remember=-1;
                   1612: my %remembered;
                   1613: my %accessed;
                   1614: my $kicks=0;
                   1615: my $hits=0;
1.849     albertel 1616: sub make_key {
                   1617:     my ($name,$id) = @_;
1.872     albertel 1618:     if (length($id) > 65 
                   1619: 	&& length(&escape($id)) > 200) {
                   1620: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1621:     }
1.849     albertel 1622:     return &escape($name.':'.$id);
                   1623: }
                   1624: 
1.599     albertel 1625: sub devalidate_cache_new {
                   1626:     my ($name,$id,$debug) = @_;
                   1627:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1628:     $id=&make_key($name,$id);
1.599     albertel 1629:     $memcache->delete($id);
                   1630:     delete($remembered{$id});
                   1631:     delete($accessed{$id});
                   1632: }
                   1633: 
                   1634: sub is_cached_new {
                   1635:     my ($name,$id,$debug) = @_;
1.849     albertel 1636:     $id=&make_key($name,$id);
1.599     albertel 1637:     if (exists($remembered{$id})) {
                   1638: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1639: 	$accessed{$id}=[&gettimeofday()];
                   1640: 	$hits++;
                   1641: 	return ($remembered{$id},1);
                   1642:     }
                   1643:     my $value = $memcache->get($id);
                   1644:     if (!(defined($value))) {
                   1645: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1646: 	return (undef,undef);
1.416     albertel 1647:     }
1.599     albertel 1648:     if ($value eq '__undef__') {
                   1649: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1650: 	$value=undef;
                   1651:     }
                   1652:     &make_room($id,$value,$debug);
                   1653:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1654:     return ($value,1);
                   1655: }
                   1656: 
                   1657: sub do_cache_new {
                   1658:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1659:     $id=&make_key($name,$id);
1.599     albertel 1660:     my $setvalue=$value;
                   1661:     if (!defined($setvalue)) {
                   1662: 	$setvalue='__undef__';
                   1663:     }
1.623     albertel 1664:     if (!defined($time) ) {
                   1665: 	$time=600;
                   1666:     }
1.599     albertel 1667:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1668:     my $result = $memcache->set($id,$setvalue,$time);
                   1669:     if (! $result) {
1.872     albertel 1670: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1671: 	$memcache->disconnect_all();
1.872     albertel 1672:     }
1.600     albertel 1673:     # need to make a copy of $value
1.919     albertel 1674:     &make_room($id,$value,$debug);
1.599     albertel 1675:     return $value;
                   1676: }
                   1677: 
                   1678: sub make_room {
                   1679:     my ($id,$value,$debug)=@_;
1.919     albertel 1680: 
                   1681:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1682:                                     : $value;
1.599     albertel 1683:     if ($to_remember<0) { return; }
                   1684:     $accessed{$id}=[&gettimeofday()];
                   1685:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1686:     my $to_kick;
                   1687:     my $max_time=0;
                   1688:     foreach my $other (keys(%accessed)) {
                   1689: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1690: 	    $to_kick=$other;
                   1691: 	    $max_time=&tv_interval($accessed{$other});
                   1692: 	}
                   1693:     }
                   1694:     delete($remembered{$to_kick});
                   1695:     delete($accessed{$to_kick});
                   1696:     $kicks++;
                   1697:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1698:     return;
                   1699: }
                   1700: 
1.599     albertel 1701: sub purge_remembered {
1.604     albertel 1702:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1703:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1704:     undef(%remembered);
                   1705:     undef(%accessed);
1.428     albertel 1706: }
1.70      www      1707: # ------------------------------------- Read an entry from a user's environment
                   1708: 
                   1709: sub userenvironment {
                   1710:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1711:     my $items;
                   1712:     foreach my $item (@what) {
                   1713:         $items.=&escape($item).'&';
                   1714:     }
                   1715:     $items=~s/\&$//;
1.70      www      1716:     my %returnhash=();
1.1009    raeburn  1717:     my $uhome = &homeserver($unam,$udom);
                   1718:     unless ($uhome eq 'no_host') {
                   1719:         my @answer=split(/\&/, 
                   1720:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
                   1721:         my $i;
                   1722:         for ($i=0;$i<=$#what;$i++) {
                   1723: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1724:         }
1.70      www      1725:     }
                   1726:     return %returnhash;
1.1       albertel 1727: }
                   1728: 
1.617     albertel 1729: # ---------------------------------------------------------- Get a studentphoto
                   1730: sub studentphoto {
                   1731:     my ($udom,$unam,$ext) = @_;
                   1732:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1733:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1734:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1735:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1736:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1737:             } else {
                   1738:                 my ($result,$perm_reqd)=
1.707     albertel 1739: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1740:                 if ($result eq 'ok') {
                   1741:                     if (!($perm_reqd eq 'yes')) {
                   1742:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1743:                     }
                   1744:                 }
                   1745:             }
                   1746:         }
                   1747:     } else {
                   1748:         my ($result,$perm_reqd) = 
1.707     albertel 1749: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1750:         if ($result eq 'ok') {
                   1751:             if (!($perm_reqd eq 'yes')) {
                   1752:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1753:             }
                   1754:         }
                   1755:     }
                   1756:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1757: }
                   1758: 
                   1759: sub retrievestudentphoto {
                   1760:     my ($udom,$unam,$ext,$type) = @_;
                   1761:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1762:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1763:     if ($ret eq 'ok') {
                   1764:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1765:         if ($type eq 'thumbnail') {
                   1766:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1767:         }
                   1768:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1769:         return $tokenurl;
                   1770:     } else {
                   1771:         if ($type eq 'thumbnail') {
                   1772:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1773:         } else { 
                   1774:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1775:         }
1.617     albertel 1776:     }
                   1777: }
                   1778: 
1.263     www      1779: # -------------------------------------------------------------------- New chat
                   1780: 
                   1781: sub chatsend {
1.724     raeburn  1782:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1783:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1784:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1785:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1786:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1787: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1788: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1789: }
                   1790: 
                   1791: # ------------------------------------------ Find current version of a resource
                   1792: 
                   1793: sub getversion {
                   1794:     my $fname=&clutter(shift);
                   1795:     unless ($fname=~/^\/res\//) { return -1; }
                   1796:     return &currentversion(&filelocation('',$fname));
                   1797: }
                   1798: 
                   1799: sub currentversion {
                   1800:     my $fname=shift;
1.599     albertel 1801:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1802:     if (defined($cached)) { return $result; }
1.292     www      1803:     my $author=$fname;
                   1804:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1805:     my ($udom,$uname)=split(/\//,$author);
                   1806:     my $home=homeserver($uname,$udom);
                   1807:     if ($home eq 'no_host') { 
                   1808:         return -1; 
                   1809:     }
                   1810:     my $answer=reply("currentversion:$fname",$home);
                   1811:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1812: 	return -1;
                   1813:     }
1.599     albertel 1814:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1815: }
                   1816: 
1.1       albertel 1817: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1818: 
1.1       albertel 1819: sub subscribe {
                   1820:     my $fname=shift;
1.761     raeburn  1821:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1822:     $fname=~s/[\n\r]//g;
1.1       albertel 1823:     my $author=$fname;
                   1824:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1825:     my ($udom,$uname)=split(/\//,$author);
                   1826:     my $home=homeserver($uname,$udom);
1.335     albertel 1827:     if ($home eq 'no_host') {
                   1828:         return 'not_found';
1.1       albertel 1829:     }
                   1830:     my $answer=reply("sub:$fname",$home);
1.64      www      1831:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1832: 	$answer.=' by '.$home;
                   1833:     }
1.1       albertel 1834:     return $answer;
                   1835: }
                   1836:     
1.8       www      1837: # -------------------------------------------------------------- Replicate file
                   1838: 
                   1839: sub repcopy {
                   1840:     my $filename=shift;
1.23      www      1841:     $filename=~s/\/+/\//g;
1.607     raeburn  1842:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1843:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1844:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1845: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1846: 	return &repcopy_userfile($filename);
                   1847:     }
1.532     albertel 1848:     $filename=~s/[\n\r]//g;
1.8       www      1849:     my $transname="$filename.in.transfer";
1.828     www      1850: # FIXME: this should flock
1.607     raeburn  1851:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1852:     my $remoteurl=subscribe($filename);
1.64      www      1853:     if ($remoteurl =~ /^con_lost by/) {
                   1854: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1855:            return 'unavailable';
1.8       www      1856:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1857: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1858: 	   return 'not_found';
1.64      www      1859:     } elsif ($remoteurl =~ /^rejected by/) {
                   1860: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1861:            return 'forbidden';
1.20      www      1862:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1863:            return 'ok';
1.8       www      1864:     } else {
1.290     www      1865:         my $author=$filename;
                   1866:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1867:         my ($udom,$uname)=split(/\//,$author);
                   1868:         my $home=homeserver($uname,$udom);
                   1869:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1870:            my @parts=split(/\//,$filename);
                   1871:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1872:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1873:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1874: 	       return 'bad_request';
1.8       www      1875:            }
                   1876:            my $count;
                   1877:            for ($count=5;$count<$#parts;$count++) {
                   1878:                $path.="/$parts[$count]";
                   1879:                if ((-e $path)!=1) {
                   1880: 		   mkdir($path,0777);
                   1881:                }
                   1882:            }
                   1883:            my $ua=new LWP::UserAgent;
                   1884:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1885:            my $response=$ua->request($request,$transname);
                   1886:            if ($response->is_error()) {
                   1887: 	       unlink($transname);
                   1888:                my $message=$response->status_line;
1.672     albertel 1889:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1890:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1891:                return 'unavailable';
1.8       www      1892:            } else {
1.16      www      1893: 	       if ($remoteurl!~/\.meta$/) {
                   1894:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1895:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1896:                   if ($mresponse->is_error()) {
                   1897: 		      unlink($filename.'.meta');
                   1898:                       &logthis(
1.672     albertel 1899:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1900:                   }
                   1901: 	       }
1.8       www      1902:                rename($transname,$filename);
1.607     raeburn  1903:                return 'ok';
1.8       www      1904:            }
1.290     www      1905:        }
1.8       www      1906:     }
1.330     www      1907: }
                   1908: 
                   1909: # ------------------------------------------------ Get server side include body
                   1910: sub ssi_body {
1.381     albertel 1911:     my ($filelink,%form)=@_;
1.606     matthew  1912:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1913:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1914:     }
1.953     www      1915:     my $output='';
                   1916:     my $response;
1.980     raeburn  1917:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1918:        ($output,$response)=&externalssi($filelink);
1.953     www      1919:     } else {
1.1004    droeschl 1920:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1921:        $filelink .= 'inhibitmenu=yes';
1.953     www      1922:        ($output,$response)=&ssi($filelink,%form);
                   1923:     }
1.778     albertel 1924:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1925:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1926:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1927:     if (wantarray) {
                   1928:         return ($output, $response);
                   1929:     } else {
                   1930:         return $output;
                   1931:     }
1.8       www      1932: }
                   1933: 
1.15      www      1934: # --------------------------------------------------------- Server Side Include
                   1935: 
1.782     albertel 1936: sub absolute_url {
                   1937:     my ($host_name) = @_;
                   1938:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1939:     if ($host_name eq '') {
                   1940: 	$host_name = $ENV{'SERVER_NAME'};
                   1941:     }
                   1942:     return $protocol.$host_name;
                   1943: }
                   1944: 
1.942     foxr     1945: #
                   1946: #   Server side include.
                   1947: # Parameters:
                   1948: #  fn     Possibly encrypted resource name/id.
                   1949: #  form   Hash that describes how the rendering should be done
                   1950: #         and other things.
1.944     foxr     1951: # Returns:
1.950     raeburn  1952: #   Scalar context: The content of the response.
                   1953: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1954: #     
1.15      www      1955: sub ssi {
                   1956: 
1.944     foxr     1957:     my ($fn,%form)=@_;
1.15      www      1958:     my $ua=new LWP::UserAgent;
1.23      www      1959:     my $request;
1.711     albertel 1960: 
                   1961:     $form{'no_update_last_known'}=1;
1.895     albertel 1962:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1963:     if (%form) {
1.782     albertel 1964:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1965:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1966:     } else {
1.782     albertel 1967:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1968:     }
                   1969: 
1.15      www      1970:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1971:     my $response=$ua->request($request);
                   1972: 
1.944     foxr     1973:     if (wantarray) {
                   1974: 	return ($response->content, $response);
                   1975:     } else {
                   1976: 	return $response->content;
1.942     foxr     1977:     }
1.324     www      1978: }
                   1979: 
                   1980: sub externalssi {
                   1981:     my ($url)=@_;
                   1982:     my $ua=new LWP::UserAgent;
                   1983:     my $request=new HTTP::Request('GET',$url);
                   1984:     my $response=$ua->request($request);
1.954     raeburn  1985:     if (wantarray) {
                   1986:         return ($response->content, $response);
                   1987:     } else {
                   1988:         return $response->content;
                   1989:     }
1.15      www      1990: }
1.254     www      1991: 
1.492     albertel 1992: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1993: 
                   1994: sub allowuploaded {
                   1995:     my ($srcurl,$url)=@_;
                   1996:     $url=&clutter(&declutter($url));
                   1997:     my $dir=$url;
                   1998:     $dir=~s/\/[^\/]+$//;
                   1999:     my %httpref=();
                   2000:     my $httpurl=&hreflocation('',$url);
                   2001:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2002:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2003: }
1.477     raeburn  2004: 
1.478     albertel 2005: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2006: # input: action, courseID, current domain, intended
1.637     raeburn  2007: #        path to file, source of file, instruction to parse file for objects,
                   2008: #        ref to hash for embedded objects,
                   2009: #        ref to hash for codebase of java objects.
                   2010: #
1.485     raeburn  2011: # output: url to file (if action was uploaddoc), 
                   2012: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2013: #
1.478     albertel 2014: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2015: # course.
1.477     raeburn  2016: #
1.478     albertel 2017: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2018: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2019: #          course's home server.
1.477     raeburn  2020: #
1.478     albertel 2021: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2022: #          be copied from $source (current location) to 
                   2023: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2024: #         and will then be copied to
                   2025: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2026: #         course's home server.
1.485     raeburn  2027: #
1.481     raeburn  2028: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2029: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2030: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2031: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2032: #         in course's home server.
1.637     raeburn  2033: #
1.477     raeburn  2034: 
                   2035: sub process_coursefile {
1.638     albertel 2036:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2037:     my $fetchresult;
1.638     albertel 2038:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2039:     if ($action eq 'propagate') {
1.638     albertel 2040:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2041: 			     $home);
1.481     raeburn  2042:     } else {
1.477     raeburn  2043:         my $fpath = '';
                   2044:         my $fname = $file;
1.478     albertel 2045:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2046:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2047:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2048:         if ($action eq 'copy') {
                   2049:             if ($source eq '') {
                   2050:                 $fetchresult = 'no source file';
                   2051:                 return $fetchresult;
                   2052:             } else {
                   2053:                 my $destination = $filepath.'/'.$fname;
                   2054:                 rename($source,$destination);
                   2055:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2056:                                  $home);
1.481     raeburn  2057:             }
                   2058:         } elsif ($action eq 'uploaddoc') {
                   2059:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2060:             print $fh $env{'form.'.$source};
1.481     raeburn  2061:             close($fh);
1.637     raeburn  2062:             if ($parser eq 'parse') {
1.1024    raeburn  2063:                 my $mm = new File::MMagic;
                   2064:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2065:                 if ($mime_type eq 'text/html') {
                   2066:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2067:                     unless ($parse_result eq 'ok') {
                   2068:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2069:                     }
1.637     raeburn  2070:                 }
                   2071:             }
1.477     raeburn  2072:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2073:                                  $home);
1.481     raeburn  2074:             if ($fetchresult eq 'ok') {
                   2075:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2076:             } else {
                   2077:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2078:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2079:                 return '/adm/notfound.html';
                   2080:             }
1.477     raeburn  2081:         }
                   2082:     }
1.485     raeburn  2083:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2084:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2085:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2086:     }
                   2087:     return $fetchresult;
                   2088: }
                   2089: 
1.637     raeburn  2090: sub build_filepath {
                   2091:     my ($fpath) = @_;
                   2092:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2093:     unless ($fpath eq '') {
                   2094:         my @parts=split('/',$fpath);
                   2095:         foreach my $part (@parts) {
                   2096:             $filepath.= '/'.$part;
                   2097:             if ((-e $filepath)!=1) {
                   2098:                 mkdir($filepath,0777);
                   2099:             }
                   2100:         }
                   2101:     }
                   2102:     return $filepath;
                   2103: }
                   2104: 
                   2105: sub store_edited_file {
1.638     albertel 2106:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2107:     my $file = $primary_url;
                   2108:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2109:     my $fpath = '';
                   2110:     my $fname = $file;
                   2111:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2112:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2113:     my $filepath = &build_filepath($fpath);
                   2114:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2115:     print $fh $content;
                   2116:     close($fh);
1.638     albertel 2117:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2118:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2119: 			  $home);
1.637     raeburn  2120:     if ($$fetchresult eq 'ok') {
                   2121:         return '/uploaded/'.$fpath.'/'.$fname;
                   2122:     } else {
1.638     albertel 2123:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2124: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2125:         return '/adm/notfound.html';
                   2126:     }
                   2127: }
                   2128: 
1.531     albertel 2129: sub clean_filename {
1.831     albertel 2130:     my ($fname,$args)=@_;
1.315     www      2131: # Replace Windows backslashes by forward slashes
1.257     www      2132:     $fname=~s/\\/\//g;
1.831     albertel 2133:     if (!$args->{'keep_path'}) {
                   2134:         # Get rid of everything but the actual filename
                   2135: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2136:     }
1.315     www      2137: # Replace spaces by underscores
                   2138:     $fname=~s/\s+/\_/g;
                   2139: # Replace all other weird characters by nothing
1.831     albertel 2140:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2141: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2142: # numbers
                   2143:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2144:     return $fname;
                   2145: }
1.984     neumanie 2146: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2147: sub resizeImage {
                   2148: 	my($img_url) = @_;	
                   2149: 	my $ima = Image::Magick->new;                       
                   2150:         $ima->Read($img_url);
                   2151: 	if($ima->Get('width') > 400)
                   2152: 	{
                   2153: 		my $factor = $ima->Get('width')/400;
                   2154:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2155: 	}
                   2156: 	if($ima->Get('height') > 500)
                   2157:         {
                   2158:         	my $factor = $ima->Get('height')/500;
                   2159:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2160:         } 
                   2161: 		
                   2162: 	$ima->Write($img_url);
                   2163: }
1.531     albertel 2164: 
1.977     amueller 2165: #Wrapper function for userphotoupload
                   2166: sub userphotoupload
                   2167: {
                   2168: 	my($formname,$subdir) = @_;
                   2169: 	$upload_photo_form = 1;
                   2170: 	return &userfileupload($formname,undef,$subdir);
                   2171: }
                   2172: 
1.608     albertel 2173: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2174: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2175: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2176: #        $coursedoc - if true up to the current course
                   2177: #                     if false
                   2178: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2179: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2180: #        $allfiles - reference to hash for embedded objects
                   2181: #        $codebase - reference to hash for codebase of java objects
                   2182: #        $desuname - username for permanent storage of uploaded file
                   2183: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2184: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2185: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2186: # 
1.686     albertel 2187: # output: url of file in userspace, or error: <message> 
                   2188: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2189: 
                   2190: 
1.531     albertel 2191: sub userfileupload {
1.860     raeburn  2192:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2193:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2194:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2195:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2196:     $fname=&clean_filename($fname);
1.315     www      2197: # See if there is anything left
1.257     www      2198:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2199:     chop($env{'form.'.$formname});
1.523     raeburn  2200:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2201:         my $now = time;
                   2202:         my $filepath = 'tmp/helprequests/'.$now;
                   2203:         my @parts=split(/\//,$filepath);
                   2204:         my $fullpath = $perlvar{'lonDaemons'};
                   2205:         for (my $i=0;$i<@parts;$i++) {
                   2206:             $fullpath .= '/'.$parts[$i];
                   2207:             if ((-e $fullpath)!=1) {
                   2208:                 mkdir($fullpath,0777);
                   2209:             }
                   2210:         }
                   2211:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2212:         print $fh $env{'form.'.$formname};
1.523     raeburn  2213:         close($fh);
1.741     raeburn  2214:         return $fullpath.'/'.$fname;
                   2215:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2216:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2217:                        '_'.$env{'user.domain'}.'/pending';
                   2218:         my @parts=split(/\//,$filepath);
                   2219:         my $fullpath = $perlvar{'lonDaemons'};
                   2220:         for (my $i=0;$i<@parts;$i++) {
                   2221:             $fullpath .= '/'.$parts[$i];
                   2222:             if ((-e $fullpath)!=1) {
                   2223:                 mkdir($fullpath,0777);
                   2224:             }
                   2225:         }
                   2226:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2227:         print $fh $env{'form.'.$formname};
                   2228:         close($fh);
                   2229:         return $fullpath.'/'.$fname;
1.523     raeburn  2230:     }
1.995     raeburn  2231:     if ($subdir eq 'scantron') {
                   2232:         $fname = 'scantron_orig_'.$fname;
                   2233:     } else {   
1.258     www      2234: # Create the directory if not present
1.995     raeburn  2235:         $fname="$subdir/$fname";
                   2236:     }
1.259     www      2237:     if ($coursedoc) {
1.638     albertel 2238: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2239: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2240:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2241:             return &finishuserfileupload($docuname,$docudom,
                   2242: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2243: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2244:         } else {
1.620     albertel 2245:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2246:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2247: 				       $fname,$formname,$parser,
                   2248: 				       $allfiles,$codebase);
1.481     raeburn  2249:         }
1.719     banghart 2250:     } elsif (defined($destuname)) {
                   2251:         my $docuname=$destuname;
                   2252:         my $docudom=$destudom;
1.860     raeburn  2253: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2254: 				     $parser,$allfiles,$codebase,
                   2255:                                      $thumbwidth,$thumbheight);
1.719     banghart 2256:         
1.259     www      2257:     } else {
1.638     albertel 2258:         my $docuname=$env{'user.name'};
                   2259:         my $docudom=$env{'user.domain'};
1.714     raeburn  2260:         if (exists($env{'form.group'})) {
                   2261:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2262:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2263:         }
1.860     raeburn  2264: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2265: 				     $parser,$allfiles,$codebase,
                   2266:                                      $thumbwidth,$thumbheight);
1.259     www      2267:     }
1.271     www      2268: }
                   2269: 
                   2270: sub finishuserfileupload {
1.860     raeburn  2271:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2272:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2273:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2274:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2275:   
1.860     raeburn  2276:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2277:     $file=$fname;
                   2278:     if ($fname=~m|/|) {
                   2279:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2280: 	$path.=$fnamepath.'/';
                   2281:     }
1.259     www      2282:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2283:     my $count;
                   2284:     for ($count=4;$count<=$#parts;$count++) {
                   2285:         $filepath.="/$parts[$count]";
                   2286:         if ((-e $filepath)!=1) {
                   2287: 	    mkdir($filepath,0777);
                   2288:         }
                   2289:     }
1.984     neumanie 2290: 
1.258     www      2291: # Save the file
                   2292:     {
1.701     albertel 2293: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2294: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2295: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2296: 	    return '/adm/notfound.html';
                   2297: 	}
                   2298: 	if (!print FH ($env{'form.'.$formname})) {
                   2299: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2300: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2301: 	    return '/adm/notfound.html';
                   2302: 	}
1.570     albertel 2303: 	close(FH);
1.977     amueller 2304: 	if($upload_photo_form==1)
                   2305: 	{
1.984     neumanie 2306: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2307: 		$upload_photo_form = 0;
                   2308: 	}
1.258     www      2309:     }
1.637     raeburn  2310:     if ($parser eq 'parse') {
1.1024    raeburn  2311:         my $mm = new File::MMagic;
                   2312:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2313:         if ($mime_type eq 'text/html') {
                   2314:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2315:                                                        $allfiles,$codebase);
                   2316:             unless ($parse_result eq 'ok') {
                   2317:                 &logthis('Failed to parse '.$filepath.$file.
                   2318: 	   	         ' for embedded media: '.$parse_result); 
                   2319:             }
1.637     raeburn  2320:         }
                   2321:     }
1.860     raeburn  2322:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2323:         my $input = $filepath.'/'.$file;
                   2324:         my $output = $filepath.'/'.'tn-'.$file;
                   2325:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2326:         system("convert -sample $thumbsize $input $output");
                   2327:         if (-e $filepath.'/'.'tn-'.$file) {
                   2328:             $fetchthumb  = 1; 
                   2329:         }
                   2330:     }
1.858     raeburn  2331:  
1.259     www      2332: # Notify homeserver to grep it
                   2333: #
1.984     neumanie 2334:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2335:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2336:     if ($fetchresult eq 'ok') {
1.860     raeburn  2337:         if ($fetchthumb) {
                   2338:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2339:             if ($thumbresult ne 'ok') {
                   2340:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2341:                          $docuhome.': '.$thumbresult);
                   2342:             }
                   2343:         }
1.259     www      2344: #
1.258     www      2345: # Return the URL to it
1.494     albertel 2346:         return '/uploaded/'.$path.$file;
1.263     www      2347:     } else {
1.494     albertel 2348:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2349: 		 ': '.$fetchresult);
1.263     www      2350:         return '/adm/notfound.html';
1.858     raeburn  2351:     }
1.493     albertel 2352: }
                   2353: 
1.637     raeburn  2354: sub extract_embedded_items {
1.961     raeburn  2355:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2356:     my @state = ();
                   2357:     my %javafiles = (
                   2358:                       codebase => '',
                   2359:                       code => '',
                   2360:                       archive => ''
                   2361:                     );
                   2362:     my %mediafiles = (
                   2363:                       src => '',
                   2364:                       movie => '',
                   2365:                      );
1.648     raeburn  2366:     my $p;
                   2367:     if ($content) {
                   2368:         $p = HTML::LCParser->new($content);
                   2369:     } else {
1.961     raeburn  2370:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2371:     }
1.641     albertel 2372:     while (my $t=$p->get_token()) {
1.640     albertel 2373: 	if ($t->[0] eq 'S') {
                   2374: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2375: 	    push(@state, $tagname);
1.648     raeburn  2376:             if (lc($tagname) eq 'allow') {
                   2377:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2378:             }
1.640     albertel 2379: 	    if (lc($tagname) eq 'img') {
                   2380: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2381: 	    }
1.886     albertel 2382: 	    if (lc($tagname) eq 'a') {
                   2383: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2384: 	    }
1.645     raeburn  2385:             if (lc($tagname) eq 'script') {
                   2386:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2387:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2388:                 } else {
                   2389:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2390:                 }
                   2391:             }
                   2392:             if (lc($tagname) eq 'link') {
                   2393:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2394:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2395:                 }
                   2396:             }
1.640     albertel 2397: 	    if (lc($tagname) eq 'object' ||
                   2398: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2399: 		foreach my $item (keys(%javafiles)) {
                   2400: 		    $javafiles{$item} = '';
                   2401: 		}
                   2402: 	    }
                   2403: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2404: 		my $name = lc($attr->{'name'});
                   2405: 		foreach my $item (keys(%javafiles)) {
                   2406: 		    if ($name eq $item) {
                   2407: 			$javafiles{$item} = $attr->{'value'};
                   2408: 			last;
                   2409: 		    }
                   2410: 		}
                   2411: 		foreach my $item (keys(%mediafiles)) {
                   2412: 		    if ($name eq $item) {
                   2413: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2414: 			last;
                   2415: 		    }
                   2416: 		}
                   2417: 	    }
                   2418: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2419: 		foreach my $item (keys(%javafiles)) {
                   2420: 		    if ($attr->{$item}) {
                   2421: 			$javafiles{$item} = $attr->{$item};
                   2422: 			last;
                   2423: 		    }
                   2424: 		}
                   2425: 		foreach my $item (keys(%mediafiles)) {
                   2426: 		    if ($attr->{$item}) {
                   2427: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2428: 			last;
                   2429: 		    }
                   2430: 		}
                   2431: 	    }
                   2432: 	} elsif ($t->[0] eq 'E') {
                   2433: 	    my ($tagname) = ($t->[1]);
                   2434: 	    if ($javafiles{'codebase'} ne '') {
                   2435: 		$javafiles{'codebase'} .= '/';
                   2436: 	    }  
                   2437: 	    if (lc($tagname) eq 'applet' ||
                   2438: 		lc($tagname) eq 'object' ||
                   2439: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2440: 		) {
                   2441: 		foreach my $item (keys(%javafiles)) {
                   2442: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2443: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2444: 			&add_filetype($allfiles,$file,$item);
                   2445: 		    }
                   2446: 		}
                   2447: 	    } 
                   2448: 	    pop @state;
                   2449: 	}
                   2450:     }
1.637     raeburn  2451:     return 'ok';
                   2452: }
                   2453: 
1.639     albertel 2454: sub add_filetype {
                   2455:     my ($allfiles,$file,$type)=@_;
                   2456:     if (exists($allfiles->{$file})) {
                   2457: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2458: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2459: 	}
                   2460:     } else {
                   2461: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2462:     }
                   2463: }
                   2464: 
1.493     albertel 2465: sub removeuploadedurl {
1.984     neumanie 2466:     my ($url)=@_;	
                   2467:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2468:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2469: }
                   2470: 
                   2471: sub removeuserfile {
                   2472:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2473:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2474:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2475:     if ($result eq 'ok') {	
1.798     raeburn  2476:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2477:             my $metafile = $fname.'.meta';
                   2478:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2479: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2480:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2481:             my $sqlresult = 
1.823     albertel 2482:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2483:                                         'portfolio_metadata',$group,
                   2484:                                         'delete');
1.798     raeburn  2485:         }
                   2486:     }
                   2487:     return $result;
1.257     www      2488: }
1.15      www      2489: 
1.530     albertel 2490: sub mkdiruserfile {
                   2491:     my ($docuname,$docudom,$dir)=@_;
                   2492:     my $home=&homeserver($docuname,$docudom);
                   2493:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2494: }
                   2495: 
1.531     albertel 2496: sub renameuserfile {
                   2497:     my ($docuname,$docudom,$old,$new)=@_;
                   2498:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2499:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2500:                         &escape("$old").':'.&escape("$new"),$home);
                   2501:     if ($result eq 'ok') {
                   2502:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2503:             my $oldmeta = $old.'.meta';
                   2504:             my $newmeta = $new.'.meta';
                   2505:             my $metaresult = 
                   2506:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2507: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2509:             my $sqlresult = 
1.823     albertel 2510:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2511:                                         'portfolio_metadata',$group,
                   2512:                                         'delete');
1.798     raeburn  2513:         }
                   2514:     }
                   2515:     return $result;
1.531     albertel 2516: }
                   2517: 
1.14      www      2518: # ------------------------------------------------------------------------- Log
                   2519: 
                   2520: sub log {
                   2521:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2522:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2523: }
                   2524: 
                   2525: # ------------------------------------------------------------------ Course Log
1.352     www      2526: #
                   2527: # This routine flushes several buffers of non-mission-critical nature
                   2528: #
1.157     www      2529: 
                   2530: sub flushcourselogs {
1.352     www      2531:     &logthis('Flushing log buffers');
                   2532: #
                   2533: # course logs
                   2534: # This is a log of all transactions in a course, which can be used
                   2535: # for data mining purposes
                   2536: #
                   2537: # It also collects the courseid database, which lists last transaction
                   2538: # times and course titles for all courseids
                   2539: #
                   2540:     my %courseidbuffer=();
1.921     raeburn  2541:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2542:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2543: 		          &escape($courselogs{$crsid}),
                   2544: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2545: 	    delete $courselogs{$crsid};
                   2546:         } else {
                   2547:             &logthis('Failed to flush log buffer for '.$crsid);
                   2548:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2549:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2550:                         " exceeded maximum size, deleting.</font>");
                   2551:                delete $courselogs{$crsid};
                   2552:             }
1.352     www      2553:         }
1.920     raeburn  2554:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2555:             'description' => $coursedescrbuf{$crsid},
                   2556:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2557:             'type'        => $coursetypebuf{$crsid},
                   2558:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2559:         };
1.191     harris41 2560:     }
1.352     www      2561: #
                   2562: # Write course id database (reverse lookup) to homeserver of courses 
                   2563: # Is used in pickcourse
                   2564: #
1.840     albertel 2565:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2566:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2567:                                     $courseidbuffer{$crs_home},
                   2568:                                     $crs_home,'timeonly');
1.352     www      2569:     }
                   2570: #
                   2571: # File accesses
                   2572: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2573: #
1.449     matthew  2574:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2575:         if ($entry =~ /___count$/) {
                   2576:             my ($dom,$name);
1.807     albertel 2577:             ($dom,$name,undef)=
1.811     albertel 2578: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2579:             if (! defined($dom) || $dom eq '' || 
                   2580:                 ! defined($name) || $name eq '') {
1.620     albertel 2581:                 my $cid = $env{'request.course.id'};
                   2582:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2583:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2584:             }
1.450     matthew  2585:             my $value = $accesshash{$entry};
                   2586:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2587:             my %temphash=($url => $value);
1.449     matthew  2588:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2589:             if ($result eq 'ok') {
                   2590:                 delete $accesshash{$entry};
                   2591:             } elsif ($result eq 'unknown_cmd') {
                   2592:                 # Target server has old code running on it.
1.450     matthew  2593:                 my %temphash=($entry => $value);
1.449     matthew  2594:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2595:                     delete $accesshash{$entry};
                   2596:                 }
                   2597:             }
                   2598:         } else {
1.811     albertel 2599:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2600:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2601:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2602:                 delete $accesshash{$entry};
                   2603:             }
1.185     www      2604:         }
1.191     harris41 2605:     }
1.352     www      2606: #
                   2607: # Roles
                   2608: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2609: #
1.800     albertel 2610:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2611:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2612: 	    split(/\:/,$entry);
                   2613:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2614:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2615:                 $rudom,$runame) eq 'ok') {
                   2616: 	    delete $userrolehash{$entry};
                   2617:         }
                   2618:     }
1.662     raeburn  2619: #
                   2620: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2621: #
                   2622:     my %domrolebuffer = ();
1.1000    raeburn  2623:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2624:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2625:         if ($domrolebuffer{$rudom}) {
                   2626:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2627:                       '='.&escape($domainrolehash{$entry});
                   2628:         } else {
                   2629:             $domrolebuffer{$rudom}.=&escape($entry).
                   2630:                       '='.&escape($domainrolehash{$entry});
                   2631:         }
                   2632:         delete $domainrolehash{$entry};
                   2633:     }
                   2634:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2635: 	my %servers = &get_servers($dom,'library');
                   2636: 	foreach my $tryserver (keys(%servers)) {
                   2637: 	    unless (&reply('domroleput:'.$dom.':'.
                   2638: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2639: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2640: 	    }
1.662     raeburn  2641:         }
                   2642:     }
1.186     www      2643:     $dumpcount++;
1.157     www      2644: }
                   2645: 
                   2646: sub courselog {
                   2647:     my $what=shift;
1.158     www      2648:     $what=time.':'.$what;
1.620     albertel 2649:     unless ($env{'request.course.id'}) { return ''; }
                   2650:     $coursedombuf{$env{'request.course.id'}}=
                   2651:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2652:     $coursenumbuf{$env{'request.course.id'}}=
                   2653:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2654:     $coursehombuf{$env{'request.course.id'}}=
                   2655:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2656:     $coursedescrbuf{$env{'request.course.id'}}=
                   2657:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2658:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2659:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2660:     $courseownerbuf{$env{'request.course.id'}}=
                   2661:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2662:     $coursetypebuf{$env{'request.course.id'}}=
                   2663:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2664:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2665: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2666:     } else {
1.620     albertel 2667: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2668:     }
1.620     albertel 2669:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2670: 	&flushcourselogs();
                   2671:     }
1.158     www      2672: }
                   2673: 
                   2674: sub courseacclog {
                   2675:     my $fnsymb=shift;
1.620     albertel 2676:     unless ($env{'request.course.id'}) { return ''; }
                   2677:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2678:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2679:         $what.=':POST';
1.583     matthew  2680:         # FIXME: Probably ought to escape things....
1.800     albertel 2681: 	foreach my $key (keys(%env)) {
                   2682:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2683:                 my $formitem = $1;
                   2684:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2685:                     $what.=':'.$formitem.'='.$env{$key};
                   2686:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2687:                     $what.=':'.$formitem.'='.$env{$key};
                   2688:                 }
1.158     www      2689:             }
1.191     harris41 2690:         }
1.583     matthew  2691:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2692:         # FIXME: We should not be depending on a form parameter that someone
                   2693:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2694:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2695:             $what.= ':POST';
                   2696:             # FIXME: Probably ought to escape things....
                   2697:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2698:                                  'crsdiscuss') {
1.620     albertel 2699:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2700:             }
                   2701:         }
1.158     www      2702:     }
                   2703:     &courselog($what);
1.149     www      2704: }
                   2705: 
1.185     www      2706: sub countacc {
                   2707:     my $url=&declutter(shift);
1.458     matthew  2708:     return if (! defined($url) || $url eq '');
1.620     albertel 2709:     unless ($env{'request.course.id'}) { return ''; }
                   2710:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2711:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2712:     $accesshash{$key}++;
1.185     www      2713: }
1.349     www      2714: 
1.361     www      2715: sub linklog {
                   2716:     my ($from,$to)=@_;
                   2717:     $from=&declutter($from);
                   2718:     $to=&declutter($to);
                   2719:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2720:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2721: }
                   2722:   
1.349     www      2723: sub userrolelog {
                   2724:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2725:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2726:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2727:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2728:         ($trole=~/^ta/)) {
1.350     www      2729:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2730:        $userrolehash
                   2731:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2732:                     =$tend.':'.$tstart;
1.662     raeburn  2733:     }
1.898     albertel 2734:     if (($env{'request.role'} =~ /dc\./) &&
                   2735: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2736: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2737: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2738:        $userrolehash
                   2739:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2740:                     =$tend.':'.$tstart;
                   2741:     }
1.662     raeburn  2742:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2743:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2744:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2745:         ($trole=~/^sc/)) {
                   2746:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2747:        $domainrolehash
                   2748:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2749:                     = $tend.':'.$tstart;
                   2750:     }
1.351     www      2751: }
                   2752: 
1.957     raeburn  2753: sub courserolelog {
                   2754:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2755:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2756:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2757:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2758:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2759:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2760:             my $cdom = $1;
                   2761:             my $cnum = $2;
                   2762:             my $sec = $3;
                   2763:             my $namespace = 'rolelog';
                   2764:             my %storehash = (
                   2765:                                role    => $trole,
                   2766:                                start   => $tstart,
                   2767:                                end     => $tend,
                   2768:                                selfenroll => $selfenroll,
                   2769:                                context    => $context,
                   2770:                             );
                   2771:             if ($trole eq 'gr') {
                   2772:                 $namespace = 'groupslog';
                   2773:                 $storehash{'group'} = $sec;
                   2774:             } else {
                   2775:                 $storehash{'section'} = $sec;
                   2776:             }
                   2777:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2778:             if (($trole ne 'st') || ($sec ne '')) {
                   2779:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2780:             }
1.957     raeburn  2781:         }
                   2782:     }
                   2783:     return;
                   2784: }
                   2785: 
1.351     www      2786: sub get_course_adv_roles {
1.948     raeburn  2787:     my ($cid,$codes) = @_;
1.620     albertel 2788:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2789:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2790:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2791:     my %nothide=();
1.800     albertel 2792:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2793:         if ($user !~ /:/) {
                   2794: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2795:         } else {
                   2796:             $nothide{$user}=1;
                   2797:         }
1.470     www      2798:     }
1.351     www      2799:     my %returnhash=();
                   2800:     my %dumphash=
                   2801:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2802:     my $now=time;
1.997     raeburn  2803:     my %privileged;
1.1000    raeburn  2804:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2805: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2806:         if (($tstart) && ($tstart<0)) { next; }
                   2807:         if (($tend) && ($tend<$now)) { next; }
                   2808:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2809:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2810: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2811:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2812:             my %dompersonnel =
1.998     raeburn  2813:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2814:             $privileged{$domain} = {};
                   2815:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2816:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2817:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2818:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2819:                         $privileged{$udom}{$uname} = 1;
                   2820:                     }
                   2821:                 }
                   2822:             }
                   2823:         }
                   2824:         if ((exists($privileged{$domain}{$username})) && 
                   2825:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2826: 	if ($role eq 'cr') { next; }
1.948     raeburn  2827:         if ($codes) {
                   2828:             if ($section) { $role .= ':'.$section; }
                   2829:             if ($returnhash{$role}) {
                   2830:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2831:             } else {
                   2832:                 $returnhash{$role}=$username.':'.$domain;
                   2833:             }
1.351     www      2834:         } else {
1.988     raeburn  2835:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2836:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2837:             if ($returnhash{$key}) {
                   2838: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2839:             } else {
                   2840:                 $returnhash{$key}=$username.':'.$domain;
                   2841:             }
1.351     www      2842:         }
1.948     raeburn  2843:     }
1.400     www      2844:     return %returnhash;
                   2845: }
                   2846: 
                   2847: sub get_my_roles {
1.937     raeburn  2848:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2849:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2850:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2851:     my (%dumphash,%nothide);
1.858     raeburn  2852:     if ($context eq 'userroles') { 
                   2853:         %dumphash = &dump('roles',$udom,$uname);
                   2854:     } else {
                   2855:         %dumphash=
1.400     www      2856:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2857:         if ($hidepriv) {
                   2858:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2859:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2860:                 if ($user !~ /:/) {
                   2861:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2862:                 } else {
                   2863:                     $nothide{$user} = 1;
                   2864:                 }
                   2865:             }
                   2866:         }
1.858     raeburn  2867:     }
1.400     www      2868:     my %returnhash=();
                   2869:     my $now=time;
1.999     raeburn  2870:     my %privileged;
1.800     albertel 2871:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2872:         my ($role,$tend,$tstart);
                   2873:         if ($context eq 'userroles') {
                   2874: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2875:         } else {
                   2876:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2877:         }
1.400     www      2878:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2879:         my $status = 'active';
1.939     raeburn  2880:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2881:             $status = 'previous';
                   2882:         } 
                   2883:         if (($tstart) && ($now<$tstart)) {
                   2884:             $status = 'future';
                   2885:         }
                   2886:         if (ref($types) eq 'ARRAY') {
                   2887:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2888:                 next;
                   2889:             } 
                   2890:         } else {
                   2891:             if ($status ne 'active') {
                   2892:                 next;
                   2893:             }
                   2894:         }
1.867     raeburn  2895:         my ($rolecode,$username,$domain,$section,$area);
                   2896:         if ($context eq 'userroles') {
                   2897:             ($area,$rolecode) = split(/_/,$entry);
                   2898:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2899:         } else {
                   2900:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2901:         }
1.832     raeburn  2902:         if (ref($roledoms) eq 'ARRAY') {
                   2903:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2904:                 next;
                   2905:             }
                   2906:         }
                   2907:         if (ref($roles) eq 'ARRAY') {
                   2908:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2909:                 if ($role =~ /^cr\//) {
                   2910:                     if (!grep(/^cr$/,@{$roles})) {
                   2911:                         next;
                   2912:                     }
                   2913:                 } else {
                   2914:                     next;
                   2915:                 }
1.832     raeburn  2916:             }
1.867     raeburn  2917:         }
1.937     raeburn  2918:         if ($hidepriv) {
1.999     raeburn  2919:             if ($context eq 'userroles') {
                   2920:                 if ((&privileged($username,$domain)) &&
                   2921:                     (!$nothide{$username.':'.$domain})) {
                   2922:                     next;
                   2923:                 }
                   2924:             } else {
                   2925:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2926:                     my %dompersonnel =
                   2927:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2928:                     $privileged{$domain} = {};
                   2929:                     if (keys(%dompersonnel)) {
                   2930:                         foreach my $server (keys(%dompersonnel)) {
                   2931:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2932:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2933:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2934:                                     $privileged{$udom}{$uname} = $trole;
                   2935:                                 }
                   2936:                             }
                   2937:                         }
                   2938:                     }
                   2939:                 }
                   2940:                 if (exists($privileged{$domain}{$username})) {
                   2941:                     if (!$nothide{$username.':'.$domain}) {
                   2942:                         next;
                   2943:                     }
                   2944:                 }
1.937     raeburn  2945:             }
                   2946:         }
1.933     raeburn  2947:         if ($withsec) {
                   2948:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2949:                 $tstart.':'.$tend;
                   2950:         } else {
                   2951:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2952:         }
1.832     raeburn  2953:     }
1.373     www      2954:     return %returnhash;
1.399     www      2955: }
                   2956: 
                   2957: # ----------------------------------------------------- Frontpage Announcements
                   2958: #
                   2959: #
                   2960: 
                   2961: sub postannounce {
                   2962:     my ($server,$text)=@_;
1.844     albertel 2963:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2964:     unless ($text=~/\w/) { $text=''; }
                   2965:     return &reply('setannounce:'.&escape($text),$server);
                   2966: }
                   2967: 
                   2968: sub getannounce {
1.448     albertel 2969: 
                   2970:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2971: 	my $announcement='';
1.800     albertel 2972: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2973: 	close($fh);
1.399     www      2974: 	if ($announcement=~/\w/) { 
                   2975: 	    return 
                   2976:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2977:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2978: 	} else {
                   2979: 	    return '';
                   2980: 	}
                   2981:     } else {
                   2982: 	return '';
                   2983:     }
1.351     www      2984: }
1.353     www      2985: 
                   2986: # ---------------------------------------------------------- Course ID routines
                   2987: # Deal with domain's nohist_courseid.db files
                   2988: #
                   2989: 
                   2990: sub courseidput {
1.921     raeburn  2991:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2992:     my $outcome;
                   2993:     if ($caller eq 'timeonly') {
                   2994:         my $cids = '';
                   2995:         foreach my $item (keys(%$storehash)) {
                   2996:             $cids.=&escape($item).'&';
                   2997:         }
                   2998:         $cids=~s/\&$//;
                   2999:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3000:                           $coursehome);       
                   3001:     } else {
                   3002:         my $items = '';
                   3003:         foreach my $item (keys(%$storehash)) {
                   3004:             $items.= &escape($item).'='.
                   3005:                      &freeze_escape($$storehash{$item}).'&';
                   3006:         }
                   3007:         $items=~s/\&$//;
                   3008:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3009:                           $coursehome);
1.918     raeburn  3010:     }
                   3011:     if ($outcome eq 'unknown_cmd') {
                   3012:         my $what;
                   3013:         foreach my $cid (keys(%$storehash)) {
                   3014:             $what .= &escape($cid).'=';
1.921     raeburn  3015:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3016:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3017:             }
                   3018:             $what =~ s/\:$/&/;
                   3019:         }
                   3020:         $what =~ s/\&$//;  
                   3021:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3022:     } else {
                   3023:         return $outcome;
                   3024:     }
1.353     www      3025: }
                   3026: 
                   3027: sub courseiddump {
1.921     raeburn  3028:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3029:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1008    raeburn  3030:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
1.918     raeburn  3031:     my $as_hash = 1;
                   3032:     my %returnhash;
                   3033:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3034:     my %libserv = &all_library();
                   3035:     foreach my $tryserver (keys(%libserv)) {
                   3036:         if ( (  $hostidflag == 1 
                   3037: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3038: 	     || (!defined($hostidflag)) ) {
                   3039: 
1.918     raeburn  3040: 	    if (($domfilter eq '') ||
                   3041: 		(&host_domain($tryserver) eq $domfilter)) {
                   3042:                 my $rep = 
                   3043:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3044:                          $sincefilter.':'.&escape($descfilter).':'.
                   3045:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3046:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3047:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3048:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3049:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3050:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
1.918     raeburn  3051:                 my @pairs=split(/\&/,$rep);
                   3052:                 foreach my $item (@pairs) {
                   3053:                     my ($key,$value)=split(/\=/,$item,2);
                   3054:                     $key = &unescape($key);
                   3055:                     next if ($key =~ /^error: 2 /);
                   3056:                     my $result = &thaw_unescape($value);
                   3057:                     if (ref($result) eq 'HASH') {
                   3058:                         $returnhash{$key}=$result;
                   3059:                     } else {
1.921     raeburn  3060:                         my @responses = split(/:/,$value);
                   3061:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3062:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3063:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3064:                         }
1.1008    raeburn  3065:                     }
1.353     www      3066:                 }
                   3067:             }
                   3068:         }
                   3069:     }
                   3070:     return %returnhash;
                   3071: }
                   3072: 
1.658     raeburn  3073: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3074: 
                   3075: sub dcmailput {
1.685     raeburn  3076:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3077:     my $status = &Apache::lonnet::critical(
1.740     www      3078:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3079:        &escape($message),$server);
1.662     raeburn  3080:     return $status;
                   3081: }
                   3082: 
1.658     raeburn  3083: sub dcmaildump {
                   3084:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3085:     my %returnhash=();
1.846     albertel 3086: 
                   3087:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3088:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3089:                                                          &escape($enddate).':';
                   3090: 	my @esc_senders=map { &escape($_)} @$senders;
                   3091: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3092: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3093:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3094:             if (($key) && ($value)) {
                   3095:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3096:             }
                   3097:         }
                   3098:     }
                   3099:     return %returnhash;
                   3100: }
1.662     raeburn  3101: # ---------------------------------------------------------- Domain roles
                   3102: 
                   3103: sub get_domain_roles {
                   3104:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3105:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3106:         $startdate = '.';
                   3107:     }
1.1018    raeburn  3108:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3109:         $enddate = '.';
                   3110:     }
1.922     raeburn  3111:     my $rolelist;
                   3112:     if (ref($roles) eq 'ARRAY') {
                   3113:         $rolelist = join(':',@{$roles});
                   3114:     }
1.662     raeburn  3115:     my %personnel = ();
1.841     albertel 3116: 
                   3117:     my %servers = &get_servers($dom,'library');
                   3118:     foreach my $tryserver (keys(%servers)) {
                   3119: 	%{$personnel{$tryserver}}=();
                   3120: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3121: 					    &escape($startdate).':'.
                   3122: 					    &escape($enddate).':'.
                   3123: 					    &escape($rolelist), $tryserver))) {
                   3124: 	    my ($key,$value) = split(/\=/,$line,2);
                   3125: 	    if (($key) && ($value)) {
                   3126: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3127: 	    }
                   3128: 	}
1.662     raeburn  3129:     }
                   3130:     return %personnel;
                   3131: }
1.658     raeburn  3132: 
1.149     www      3133: # ----------------------------------------------------------- Check out an item
                   3134: 
1.504     albertel 3135: sub get_first_access {
                   3136:     my ($type,$argsymb)=@_;
1.790     albertel 3137:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3138:     if ($argsymb) { $symb=$argsymb; }
                   3139:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3140:     if ($type eq 'course') {
                   3141: 	$res='course';
                   3142:     } elsif ($type eq 'map') {
1.588     albertel 3143: 	$res=&symbread($map);
                   3144:     } else {
                   3145: 	$res=$symb;
                   3146:     }
                   3147:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3148:     return $times{"$courseid\0$res"};
1.504     albertel 3149: }
                   3150: 
                   3151: sub set_first_access {
                   3152:     my ($type)=@_;
1.790     albertel 3153:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3154:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3155:     if ($type eq 'course') {
                   3156: 	$res='course';
                   3157:     } elsif ($type eq 'map') {
1.588     albertel 3158: 	$res=&symbread($map);
                   3159:     } else {
                   3160: 	$res=$symb;
                   3161:     }
                   3162:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3163:     if (!$firstaccess) {
1.588     albertel 3164: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3165:     }
                   3166:     return 'already_set';
1.504     albertel 3167: }
                   3168: 
1.149     www      3169: sub checkout {
                   3170:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3171:     my $now=time;
                   3172:     my $lonhost=$perlvar{'lonHostID'};
                   3173:     my $infostr=&escape(
1.234     www      3174:                  'CHECKOUTTOKEN&'.
1.149     www      3175:                  $tuname.'&'.
                   3176:                  $tudom.'&'.
                   3177:                  $tcrsid.'&'.
                   3178:                  $symb.'&'.
                   3179: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3180:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3181:     if ($token=~/^error\:/) { 
1.672     albertel 3182:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3183:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3184:                  "</font>");
                   3185:         return ''; 
                   3186:     }
                   3187: 
1.149     www      3188:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3189:     $token=~tr/a-z/A-Z/;
                   3190: 
1.153     www      3191:     my %infohash=('resource.0.outtoken' => $token,
                   3192:                   'resource.0.checkouttime' => $now,
                   3193:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3194: 
                   3195:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3196:        return '';
1.151     www      3197:     } else {
1.672     albertel 3198:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3199:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3200:                  "</font>");
1.149     www      3201:     }    
                   3202: 
                   3203:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3204:                          &escape('Checkout '.$infostr.' - '.
                   3205:                                                  $token)) ne 'ok') {
                   3206: 	return '';
1.151     www      3207:     } else {
1.672     albertel 3208:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3209:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3210:                  "</font>");
1.149     www      3211:     }
1.151     www      3212:     return $token;
1.149     www      3213: }
                   3214: 
                   3215: # ------------------------------------------------------------ Check in an item
                   3216: 
                   3217: sub checkin {
                   3218:     my $token=shift;
1.150     www      3219:     my $now=time;
                   3220:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3221:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3222:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3223:     $dtoken=~s/\W/\_/g;
1.234     www      3224:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3225:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3226: 
1.154     www      3227:     unless (($tuname) && ($tudom)) {
                   3228:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3229:         return '';
                   3230:     }
                   3231:     
                   3232:     unless (&allowed('mgr',$tcrsid)) {
                   3233:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3234:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3235:         return '';
                   3236:     }
                   3237: 
1.153     www      3238:     my %infohash=('resource.0.intoken' => $token,
                   3239:                   'resource.0.checkintime' => $now,
                   3240:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3241: 
                   3242:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3243:        return '';
                   3244:     }    
                   3245: 
                   3246:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3247:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3248: 	return '';
                   3249:     }
                   3250: 
                   3251:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3252: }
                   3253: 
                   3254: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3255: 
                   3256: sub expirespread {
                   3257:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3258:     my $cid=$env{'request.course.id'}; 
1.110     www      3259:     if ($cid) {
                   3260:        my $now=time;
                   3261:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3262:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3263:                             $env{'course.'.$cid.'.num'}.
1.110     www      3264: 	        	    ':nohist_expirationdates:'.
                   3265:                             &escape($key).'='.$now,
1.620     albertel 3266:                             $env{'course.'.$cid.'.home'})
1.110     www      3267:     }
                   3268:     return 'ok';
1.14      www      3269: }
                   3270: 
1.109     www      3271: # ----------------------------------------------------- Devalidate Spreadsheets
                   3272: 
                   3273: sub devalidate {
1.325     www      3274:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3275:     my $cid=$env{'request.course.id'}; 
1.109     www      3276:     if ($cid) {
1.391     matthew  3277:         # delete the stored spreadsheets for
                   3278:         # - the student level sheet of this user in course's homespace
                   3279:         # - the assessment level sheet for this resource 
                   3280:         #   for this user in user's homespace
1.553     albertel 3281: 	# - current conditional state info
1.325     www      3282: 	my $key=$uname.':'.$udom.':';
1.109     www      3283:         my $status=
1.299     matthew  3284: 	    &del('nohist_calculatedsheets',
1.391     matthew  3285: 		 [$key.'studentcalc:'],
1.620     albertel 3286: 		 $env{'course.'.$cid.'.domain'},
                   3287: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3288: 		.' '.
                   3289: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3290: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3291:         unless ($status eq 'ok ok') {
                   3292:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3293:                     $uname.' at '.$udom.' for '.
1.109     www      3294: 		    $symb.': '.$status);
1.133     albertel 3295:         }
1.553     albertel 3296: 	&delenv('user.state.'.$cid);
1.109     www      3297:     }
                   3298: }
                   3299: 
1.265     albertel 3300: sub get_scalar {
                   3301:     my ($string,$end) = @_;
                   3302:     my $value;
                   3303:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3304: 	$value = $1;
                   3305:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3306: 	$value = $1;
                   3307:     }
                   3308:     return &unescape($value);
                   3309: }
                   3310: 
                   3311: sub array2str {
                   3312:   my (@array) = @_;
                   3313:   my $result=&arrayref2str(\@array);
                   3314:   $result=~s/^__ARRAY_REF__//;
                   3315:   $result=~s/__END_ARRAY_REF__$//;
                   3316:   return $result;
                   3317: }
                   3318: 
1.204     albertel 3319: sub arrayref2str {
                   3320:   my ($arrayref) = @_;
1.265     albertel 3321:   my $result='__ARRAY_REF__';
1.204     albertel 3322:   foreach my $elem (@$arrayref) {
1.265     albertel 3323:     if(ref($elem) eq 'ARRAY') {
                   3324:       $result.=&arrayref2str($elem).'&';
                   3325:     } elsif(ref($elem) eq 'HASH') {
                   3326:       $result.=&hashref2str($elem).'&';
                   3327:     } elsif(ref($elem)) {
                   3328:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3329:     } else {
                   3330:       $result.=&escape($elem).'&';
                   3331:     }
                   3332:   }
                   3333:   $result=~s/\&$//;
1.265     albertel 3334:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3335:   return $result;
                   3336: }
                   3337: 
1.168     albertel 3338: sub hash2str {
1.204     albertel 3339:   my (%hash) = @_;
                   3340:   my $result=&hashref2str(\%hash);
1.265     albertel 3341:   $result=~s/^__HASH_REF__//;
                   3342:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3343:   return $result;
                   3344: }
                   3345: 
                   3346: sub hashref2str {
                   3347:   my ($hashref)=@_;
1.265     albertel 3348:   my $result='__HASH_REF__';
1.800     albertel 3349:   foreach my $key (sort(keys(%$hashref))) {
                   3350:     if (ref($key) eq 'ARRAY') {
                   3351:       $result.=&arrayref2str($key).'=';
                   3352:     } elsif (ref($key) eq 'HASH') {
                   3353:       $result.=&hashref2str($key).'=';
                   3354:     } elsif (ref($key)) {
1.265     albertel 3355:       $result.='=';
1.800     albertel 3356:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3357:     } else {
1.800     albertel 3358: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3359:     }
                   3360: 
1.800     albertel 3361:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3362:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3363:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3364:       $result.=&hashref2str($hashref->{$key}).'&';
                   3365:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3366:        $result.='&';
1.800     albertel 3367:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3368:     } else {
1.800     albertel 3369:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3370:     }
                   3371:   }
1.168     albertel 3372:   $result=~s/\&$//;
1.265     albertel 3373:   $result .= '__END_HASH_REF__';
1.168     albertel 3374:   return $result;
                   3375: }
                   3376: 
                   3377: sub str2hash {
1.265     albertel 3378:     my ($string)=@_;
                   3379:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3380:     return %$hash;
                   3381: }
                   3382: 
                   3383: sub str2hashref {
1.168     albertel 3384:   my ($string) = @_;
1.265     albertel 3385: 
                   3386:   my %hash;
                   3387: 
                   3388:   if($string !~ /^__HASH_REF__/) {
                   3389:       if (! ($string eq '' || !defined($string))) {
                   3390: 	  $hash{'error'}='Not hash reference';
                   3391:       }
                   3392:       return (\%hash, $string);
                   3393:   }
                   3394: 
                   3395:   $string =~ s/^__HASH_REF__//;
                   3396: 
                   3397:   while($string !~ /^__END_HASH_REF__/) {
                   3398:       #key
                   3399:       my $key='';
                   3400:       if($string =~ /^__HASH_REF__/) {
                   3401:           ($key, $string)=&str2hashref($string);
                   3402:           if(defined($key->{'error'})) {
                   3403:               $hash{'error'}='Bad data';
                   3404:               return (\%hash, $string);
                   3405:           }
                   3406:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3407:           ($key, $string)=&str2arrayref($string);
                   3408:           if($key->[0] eq 'Array reference error') {
                   3409:               $hash{'error'}='Bad data';
                   3410:               return (\%hash, $string);
                   3411:           }
                   3412:       } else {
                   3413:           $string =~ s/^(.*?)=//;
1.267     albertel 3414: 	  $key=&unescape($1);
1.265     albertel 3415:       }
                   3416:       $string =~ s/^=//;
                   3417: 
                   3418:       #value
                   3419:       my $value='';
                   3420:       if($string =~ /^__HASH_REF__/) {
                   3421:           ($value, $string)=&str2hashref($string);
                   3422:           if(defined($value->{'error'})) {
                   3423:               $hash{'error'}='Bad data';
                   3424:               return (\%hash, $string);
                   3425:           }
                   3426:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3427:           ($value, $string)=&str2arrayref($string);
                   3428:           if($value->[0] eq 'Array reference error') {
                   3429:               $hash{'error'}='Bad data';
                   3430:               return (\%hash, $string);
                   3431:           }
                   3432:       } else {
                   3433: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3434:       }
                   3435:       $string =~ s/^&//;
                   3436: 
                   3437:       $hash{$key}=$value;
1.204     albertel 3438:   }
1.265     albertel 3439: 
                   3440:   $string =~ s/^__END_HASH_REF__//;
                   3441: 
                   3442:   return (\%hash, $string);
1.204     albertel 3443: }
                   3444: 
                   3445: sub str2array {
1.265     albertel 3446:     my ($string)=@_;
                   3447:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3448:     return @$array;
                   3449: }
                   3450: 
                   3451: sub str2arrayref {
1.204     albertel 3452:   my ($string) = @_;
1.265     albertel 3453:   my @array;
                   3454: 
                   3455:   if($string !~ /^__ARRAY_REF__/) {
                   3456:       if (! ($string eq '' || !defined($string))) {
                   3457: 	  $array[0]='Array reference error';
                   3458:       }
                   3459:       return (\@array, $string);
                   3460:   }
                   3461: 
                   3462:   $string =~ s/^__ARRAY_REF__//;
                   3463: 
                   3464:   while($string !~ /^__END_ARRAY_REF__/) {
                   3465:       my $value='';
                   3466:       if($string =~ /^__HASH_REF__/) {
                   3467:           ($value, $string)=&str2hashref($string);
                   3468:           if(defined($value->{'error'})) {
                   3469:               $array[0] ='Array reference error';
                   3470:               return (\@array, $string);
                   3471:           }
                   3472:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3473:           ($value, $string)=&str2arrayref($string);
                   3474:           if($value->[0] eq 'Array reference error') {
                   3475:               $array[0] ='Array reference error';
                   3476:               return (\@array, $string);
                   3477:           }
                   3478:       } else {
                   3479: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3480:       }
                   3481:       $string =~ s/^&//;
                   3482: 
                   3483:       push(@array, $value);
1.191     harris41 3484:   }
1.265     albertel 3485: 
                   3486:   $string =~ s/^__END_ARRAY_REF__//;
                   3487: 
                   3488:   return (\@array, $string);
1.168     albertel 3489: }
                   3490: 
1.167     albertel 3491: # -------------------------------------------------------------------Temp Store
                   3492: 
1.168     albertel 3493: sub tmpreset {
                   3494:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3495:   if (!$symb) {
                   3496:     $symb=&symbread();
1.620     albertel 3497:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3498:   }
                   3499:   $symb=escape($symb);
                   3500: 
1.620     albertel 3501:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3502:   $namespace=~s/\//\_/g;
                   3503:   $namespace=~s/\W//g;
                   3504: 
1.620     albertel 3505:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3506:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3507:   if ($domain eq 'public' && $stuname eq 'public') {
                   3508:       $stuname=$ENV{'REMOTE_ADDR'};
                   3509:   }
1.168     albertel 3510:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3511:   my %hash;
                   3512:   if (tie(%hash,'GDBM_File',
                   3513: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3514: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3515:     foreach my $key (keys(%hash)) {
1.180     albertel 3516:       if ($key=~ /:$symb/) {
1.168     albertel 3517: 	delete($hash{$key});
                   3518:       }
                   3519:     }
                   3520:   }
                   3521: }
                   3522: 
1.167     albertel 3523: sub tmpstore {
1.168     albertel 3524:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3525: 
                   3526:   if (!$symb) {
                   3527:     $symb=&symbread();
1.620     albertel 3528:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3529:   }
                   3530:   $symb=escape($symb);
                   3531: 
                   3532:   if (!$namespace) {
                   3533:     # I don't think we would ever want to store this for a course.
                   3534:     # it seems this will only be used if we don't have a course.
1.620     albertel 3535:     #$namespace=$env{'request.course.id'};
1.168     albertel 3536:     #if (!$namespace) {
1.620     albertel 3537:       $namespace=$env{'request.state'};
1.168     albertel 3538:     #}
                   3539:   }
                   3540:   $namespace=~s/\//\_/g;
                   3541:   $namespace=~s/\W//g;
1.620     albertel 3542:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3543:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3544:   if ($domain eq 'public' && $stuname eq 'public') {
                   3545:       $stuname=$ENV{'REMOTE_ADDR'};
                   3546:   }
1.168     albertel 3547:   my $now=time;
                   3548:   my %hash;
                   3549:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3550:   if (tie(%hash,'GDBM_File',
                   3551: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3552: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3553:     $hash{"version:$symb"}++;
                   3554:     my $version=$hash{"version:$symb"};
                   3555:     my $allkeys=''; 
                   3556:     foreach my $key (keys(%$storehash)) {
                   3557:       $allkeys.=$key.':';
1.591     albertel 3558:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3559:     }
                   3560:     $hash{"$version:$symb:timestamp"}=$now;
                   3561:     $allkeys.='timestamp';
                   3562:     $hash{"$version:keys:$symb"}=$allkeys;
                   3563:     if (untie(%hash)) {
                   3564:       return 'ok';
                   3565:     } else {
                   3566:       return "error:$!";
                   3567:     }
                   3568:   } else {
                   3569:     return "error:$!";
                   3570:   }
                   3571: }
1.167     albertel 3572: 
1.168     albertel 3573: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3574: 
1.168     albertel 3575: sub tmprestore {
                   3576:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3577: 
1.168     albertel 3578:   if (!$symb) {
                   3579:     $symb=&symbread();
1.620     albertel 3580:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3581:   }
                   3582:   $symb=escape($symb);
                   3583: 
1.620     albertel 3584:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3585: 
1.620     albertel 3586:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3587:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3588:   if ($domain eq 'public' && $stuname eq 'public') {
                   3589:       $stuname=$ENV{'REMOTE_ADDR'};
                   3590:   }
1.168     albertel 3591:   my %returnhash;
                   3592:   $namespace=~s/\//\_/g;
                   3593:   $namespace=~s/\W//g;
                   3594:   my %hash;
                   3595:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3596:   if (tie(%hash,'GDBM_File',
                   3597: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3598: 	  &GDBM_READER(),0640)) {
1.168     albertel 3599:     my $version=$hash{"version:$symb"};
                   3600:     $returnhash{'version'}=$version;
                   3601:     my $scope;
                   3602:     for ($scope=1;$scope<=$version;$scope++) {
                   3603:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3604:       my @keys=split(/:/,$vkeys);
                   3605:       my $key;
                   3606:       $returnhash{"$scope:keys"}=$vkeys;
                   3607:       foreach $key (@keys) {
1.591     albertel 3608: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3609: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3610:       }
                   3611:     }
1.168     albertel 3612:     if (!(untie(%hash))) {
                   3613:       return "error:$!";
                   3614:     }
                   3615:   } else {
                   3616:     return "error:$!";
                   3617:   }
                   3618:   return %returnhash;
1.167     albertel 3619: }
                   3620: 
1.9       www      3621: # ----------------------------------------------------------------------- Store
                   3622: 
                   3623: sub store {
1.124     www      3624:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3625:     my $home='';
                   3626: 
1.168     albertel 3627:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3628: 
1.213     www      3629:     $symb=&symbclean($symb);
1.122     albertel 3630:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3631: 
1.620     albertel 3632:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3633:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3634: 
                   3635:     &devalidate($symb,$stuname,$domain);
1.109     www      3636: 
                   3637:     $symb=escape($symb);
1.187     www      3638:     if (!$namespace) { 
1.620     albertel 3639:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3640:           return ''; 
                   3641:        } 
                   3642:     }
1.620     albertel 3643:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3644: 
                   3645:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3646:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3647: 
1.12      www      3648:     my $namevalue='';
1.800     albertel 3649:     foreach my $key (keys(%$storehash)) {
                   3650:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3651:     }
1.12      www      3652:     $namevalue=~s/\&$//;
1.187     www      3653:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3654:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3655: }
                   3656: 
1.47      www      3657: # -------------------------------------------------------------- Critical Store
                   3658: 
                   3659: sub cstore {
1.124     www      3660:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3661:     my $home='';
                   3662: 
1.168     albertel 3663:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3664: 
1.213     www      3665:     $symb=&symbclean($symb);
1.122     albertel 3666:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3667: 
1.620     albertel 3668:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3669:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3670: 
                   3671:     &devalidate($symb,$stuname,$domain);
1.109     www      3672: 
                   3673:     $symb=escape($symb);
1.187     www      3674:     if (!$namespace) { 
1.620     albertel 3675:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3676:           return ''; 
                   3677:        } 
                   3678:     }
1.620     albertel 3679:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3680: 
                   3681:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3682:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3683: 
1.47      www      3684:     my $namevalue='';
1.800     albertel 3685:     foreach my $key (keys(%$storehash)) {
                   3686:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3687:     }
1.47      www      3688:     $namevalue=~s/\&$//;
1.187     www      3689:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3690:     return critical
                   3691:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3692: }
                   3693: 
1.9       www      3694: # --------------------------------------------------------------------- Restore
                   3695: 
                   3696: sub restore {
1.124     www      3697:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3698:     my $home='';
                   3699: 
1.168     albertel 3700:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3701: 
1.122     albertel 3702:     if (!$symb) {
                   3703:       unless ($symb=escape(&symbread())) { return ''; }
                   3704:     } else {
1.213     www      3705:       $symb=&escape(&symbclean($symb));
1.122     albertel 3706:     }
1.188     www      3707:     if (!$namespace) { 
1.620     albertel 3708:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3709:           return ''; 
                   3710:        } 
                   3711:     }
1.620     albertel 3712:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3713:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3714:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3715:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3716: 
1.12      www      3717:     my %returnhash=();
1.800     albertel 3718:     foreach my $line (split(/\&/,$answer)) {
                   3719: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3720:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3721:     }
1.75      www      3722:     my $version;
                   3723:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3724:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3725:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3726:        }
1.75      www      3727:     }
1.13      www      3728:     return %returnhash;
1.34      www      3729: }
                   3730: 
                   3731: # ---------------------------------------------------------- Course Description
                   3732: 
                   3733: sub coursedescription {
1.731     albertel 3734:     my ($courseid,$args)=@_;
1.34      www      3735:     $courseid=~s/^\///;
1.49      www      3736:     $courseid=~s/\_/\//g;
1.34      www      3737:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3738:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3739:     my $normalid=$cdomain.'_'.$cnum;
                   3740:     # need to always cache even if we get errors otherwise we keep 
                   3741:     # trying and trying and trying to get the course description.
                   3742:     my %envhash=();
                   3743:     my %returnhash=();
1.731     albertel 3744:     
                   3745:     my $expiretime=600;
                   3746:     if ($env{'request.course.id'} eq $normalid) {
                   3747: 	$expiretime=120;
                   3748:     }
                   3749: 
                   3750:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3751:     if (!$args->{'freshen_cache'}
                   3752: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3753: 	foreach my $key (keys(%env)) {
                   3754: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3755: 	    my ($setting) = $1;
                   3756: 	    $returnhash{$setting} = $env{$key};
                   3757: 	}
                   3758: 	return %returnhash;
                   3759:     }
                   3760: 
                   3761:     # get the data agin
                   3762:     if (!$args->{'one_time'}) {
                   3763: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3764:     }
1.811     albertel 3765: 
1.34      www      3766:     if ($chome ne 'no_host') {
1.302     albertel 3767:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3768:        if (!exists($returnhash{'con_lost'})) {
                   3769:            $returnhash{'home'}= $chome;
                   3770: 	   $returnhash{'domain'} = $cdomain;
                   3771: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3772:            if (!defined($returnhash{'type'})) {
                   3773:                $returnhash{'type'} = 'Course';
                   3774:            }
1.130     albertel 3775:            while (my ($name,$value) = each %returnhash) {
1.53      www      3776:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3777:            }
1.270     www      3778:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3779:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3780: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3781:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3782:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3783:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3784:        }
                   3785:     }
1.731     albertel 3786:     if (!$args->{'one_time'}) {
1.949     raeburn  3787: 	&appenv(\%envhash);
1.731     albertel 3788:     }
1.302     albertel 3789:     return %returnhash;
1.461     www      3790: }
                   3791: 
                   3792: # -------------------------------------------------See if a user is privileged
                   3793: 
                   3794: sub privileged {
                   3795:     my ($username,$domain)=@_;
                   3796:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3797: 			&homeserver($username,$domain));
                   3798:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3799:     my $now=time;
                   3800:     if ($rolesdump ne '') {
1.800     albertel 3801:         foreach my $entry (split(/&/,$rolesdump)) {
                   3802: 	    if ($entry!~/^rolesdef_/) {
                   3803: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3804: 		$area=~s/\_\w\w$//;
                   3805: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3806: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3807: 		    my $active=1;
                   3808: 		    if ($tend) {
                   3809: 			if ($tend<$now) { $active=0; }
                   3810: 		    }
                   3811: 		    if ($tstart) {
                   3812: 			if ($tstart>$now) { $active=0; }
                   3813: 		    }
                   3814: 		    if ($active) { return 1; }
                   3815: 		}
                   3816: 	    }
                   3817: 	}
                   3818:     }
                   3819:     return 0;
1.9       www      3820: }
1.1       albertel 3821: 
1.103     harris41 3822: # -------------------------------------------------------- Get user privileges
1.11      www      3823: 
                   3824: sub rolesinit {
                   3825:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3826:     my %userroles;
1.11      www      3827:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3828:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3829:     my %allroles=();
1.678     raeburn  3830:     my %allgroups=();   
1.11      www      3831:     my $now=time;
1.966     raeburn  3832:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3833:     my $group_privs;
1.11      www      3834: 
                   3835:     if ($rolesdump ne '') {
1.800     albertel 3836:         foreach my $entry (split(/&/,$rolesdump)) {
                   3837: 	  if ($entry!~/^rolesdef_/) {
                   3838:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3839: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3840:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3841: 	    if ($role=~/^cr/) { 
1.807     albertel 3842: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3843: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3844: 		    ($tend,$tstart)=split('_',$trest);
                   3845: 		} else {
                   3846: 		    $trole=$role;
                   3847: 		}
1.678     raeburn  3848:             } elsif ($role =~ m|^gr/|) {
                   3849:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3850:                 ($trole,$group_privs) = split(/\//,$trole);
                   3851:                 $group_privs = &unescape($group_privs);
1.587     albertel 3852: 	    } else {
                   3853: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3854: 	    }
1.743     albertel 3855: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3856: 					 $username);
                   3857: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3858:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3859:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3860:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3861: 		my $spec=$trole.'.'.$area;
                   3862: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3863: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3864:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3865:                 } elsif ($trole eq 'gr') {
                   3866:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3867: 		} else {
1.567     raeburn  3868:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3869: 		}
1.12      www      3870:             }
1.662     raeburn  3871:           }
1.191     harris41 3872:         }
1.743     albertel 3873:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3874:         $userroles{'user.adv'}    = $adv;
                   3875: 	$userroles{'user.author'} = $author;
1.620     albertel 3876:         $env{'user.adv'}=$adv;
1.11      www      3877:     }
1.743     albertel 3878:     return \%userroles;  
1.11      www      3879: }
                   3880: 
1.567     raeburn  3881: sub set_arearole {
                   3882:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3883: # log the associated role with the area
                   3884:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3885:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3886: }
                   3887: 
                   3888: sub custom_roleprivs {
                   3889:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3890:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3891:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3892:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3893:         my ($rdummy,$roledef)=
                   3894:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3895:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3896:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3897:             if (defined($syspriv)) {
                   3898:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3899:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3900:             }
                   3901:             if ($tdomain ne '') {
                   3902:                 if (defined($dompriv)) {
                   3903:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3904:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3905:                 }
                   3906:                 if (($trest ne '') && (defined($coursepriv))) {
                   3907:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3908:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3909:                 }
                   3910:             }
                   3911:         }
                   3912:     }
                   3913: }
                   3914: 
1.678     raeburn  3915: sub group_roleprivs {
                   3916:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3917:     my $access = 1;
                   3918:     my $now = time;
                   3919:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3920:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3921:     if ($access) {
1.811     albertel 3922:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3923:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3924:     }
                   3925: }
1.567     raeburn  3926: 
                   3927: sub standard_roleprivs {
                   3928:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3929:     if (defined($pr{$trole.':s'})) {
                   3930:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3931:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3932:     }
                   3933:     if ($tdomain ne '') {
                   3934:         if (defined($pr{$trole.':d'})) {
                   3935:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3936:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3937:         }
                   3938:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3939:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3940:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3941:         }
                   3942:     }
                   3943: }
                   3944: 
                   3945: sub set_userprivs {
1.678     raeburn  3946:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3947:     my $author=0;
                   3948:     my $adv=0;
1.678     raeburn  3949:     my %grouproles = ();
                   3950:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3951:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3952:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3953:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3954:                 $trole = $1;
                   3955:                 $area = $2;
1.681     raeburn  3956:                 $sec = $3;
                   3957:                 $extendedarea = $area.$sec;
                   3958:                 if (exists($$allgroups{$area})) {
                   3959:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3960:                         my $spec = $trole.'.'.$extendedarea;
                   3961:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3962:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3963:                     }
                   3964:                 }
                   3965:             }
                   3966:         }
                   3967:     }
1.800     albertel 3968:     foreach my $group (keys(%grouproles)) {
                   3969:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3970:     }
1.800     albertel 3971:     foreach my $role (keys(%{$allroles})) {
                   3972:         my %thesepriv;
1.941     raeburn  3973:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3974:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3975:             if ($item ne '') {
                   3976:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3977:                 if ($restrictions eq '') {
                   3978:                     $thesepriv{$privilege}='F';
                   3979:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3980:                     $thesepriv{$privilege}.=$restrictions;
                   3981:                 }
                   3982:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3983:             }
                   3984:         }
                   3985:         my $thesestr='';
1.800     albertel 3986:         foreach my $priv (keys(%thesepriv)) {
                   3987: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3988: 	}
                   3989:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3990:     }
                   3991:     return ($author,$adv);
                   3992: }
                   3993: 
1.994     raeburn  3994: sub role_status {
1.1002    raeburn  3995:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  3996:     my @pwhere = ();
                   3997:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   3998:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   3999:         unless (!defined($$role) || $$role eq '') {
                   4000:             $$where=join('.',@pwhere);
                   4001:             $$trolecode=$$role.'.'.$$where;
                   4002:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4003:             $$tstatus='is';
                   4004:             if ($$tstart && $$tstart>$then) {
                   4005:                 $$tstatus='future';
1.1002    raeburn  4006:                 if ($$tstart && $$tstart>$refresh) {
                   4007:                     if ($$tstart<$now) {
                   4008:                         if (($$where ne '') && ($$role ne '')) {
                   4009:                             my (%allroles,%allgroups,$group_privs);
                   4010:                             my %userroles = (
                   4011:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4012:                             );
                   4013:                             my $spec=$$role.'.'.$$where;
                   4014:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4015:                             if ($$role eq 'gr') {
                   4016:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4017:                                                     $env{'user.name'})=@_;
                   4018:                                 my ($trole) = split('_',$role,1);
                   4019:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4020:                                 $group_privs = &unescape($group_privs);
                   4021:                             }
                   4022:                             if ($$role =~ /^cr\//) {
                   4023:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   4024:                             } elsif ($$role eq 'gr') {
                   4025:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4026:                                                     $env{'user.name'});
                   4027:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   4028:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4029:                                 $group_privs = &unescape($group_privs);
                   4030:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   4031:                             } else {
                   4032:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4033:                             }
                   4034:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4035:                             &appenv(\%userroles,[$$role,'cm']);
                   4036:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4037:                             $$tstatus = 'is';
                   4038:                         }
                   4039:                     }
                   4040:                 }
1.994     raeburn  4041:             }
                   4042:             if ($$tend) {
                   4043:                 if ($$tend<$then) {
                   4044:                     $$tstatus='expired';
                   4045:                 } elsif ($$tend<$now) {
                   4046:                     $$tstatus='will_not';
                   4047:                 }
                   4048:             }
                   4049:         }
                   4050:     }
                   4051: }
                   4052: 
                   4053: sub check_adhoc_privs {
1.1002    raeburn  4054:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4055:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4056:     if ($env{$cckey}) {
                   4057:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4058:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4059:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4060:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4061:         }
                   4062:     } else {
                   4063:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4064:     }
                   4065: }
                   4066: 
                   4067: sub set_adhoc_privileges {
                   4068: # role can be cc or ca
                   4069:     my ($dcdom,$pickedcourse,$role) = @_;
                   4070:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4071:     my $spec = $role.'.'.$area;
                   4072:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4073:                                   $env{'user.name'});
                   4074:     my %ccrole = ();
                   4075:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4076:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4077:     &appenv(\%userroles,[$role,'cm']);
                   4078:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4079:     &appenv( {'request.role'        => $spec,
                   4080:               'request.role.domain' => $dcdom,
                   4081:               'request.course.sec'  => ''
                   4082:              }
                   4083:            );
                   4084:     my $tadv=0;
                   4085:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4086:     &appenv({'request.role.adv'    => $tadv});
                   4087: }
                   4088: 
1.12      www      4089: # --------------------------------------------------------------- get interface
                   4090: 
                   4091: sub get {
1.131     albertel 4092:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4093:    my $items='';
1.800     albertel 4094:    foreach my $item (@$storearr) {
                   4095:        $items.=&escape($item).'&';
1.191     harris41 4096:    }
1.12      www      4097:    $items=~s/\&$//;
1.620     albertel 4098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4099:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4100:    my $uhome=&homeserver($uname,$udomain);
                   4101: 
1.133     albertel 4102:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4103:    my @pairs=split(/\&/,$rep);
1.273     albertel 4104:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4105:      return @pairs;
                   4106:    }
1.15      www      4107:    my %returnhash=();
1.42      www      4108:    my $i=0;
1.800     albertel 4109:    foreach my $item (@$storearr) {
                   4110:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4111:       $i++;
1.191     harris41 4112:    }
1.15      www      4113:    return %returnhash;
1.27      www      4114: }
                   4115: 
                   4116: # --------------------------------------------------------------- del interface
                   4117: 
                   4118: sub del {
1.133     albertel 4119:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4120:    my $items='';
1.800     albertel 4121:    foreach my $item (@$storearr) {
                   4122:        $items.=&escape($item).'&';
1.191     harris41 4123:    }
1.984     neumanie 4124: 
1.27      www      4125:    $items=~s/\&$//;
1.620     albertel 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4127:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4128:    my $uhome=&homeserver($uname,$udomain);
                   4129:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4130: }
                   4131: 
                   4132: # -------------------------------------------------------------- dump interface
                   4133: 
                   4134: sub dump {
1.755     albertel 4135:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4136:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4137:     if (!$uname) { $uname=$env{'user.name'}; }
                   4138:     my $uhome=&homeserver($uname,$udomain);
                   4139:     if ($regexp) {
                   4140: 	$regexp=&escape($regexp);
                   4141:     } else {
                   4142: 	$regexp='.';
                   4143:     }
                   4144:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4145:     my @pairs=split(/\&/,$rep);
                   4146:     my %returnhash=();
                   4147:     foreach my $item (@pairs) {
                   4148: 	my ($key,$value)=split(/=/,$item,2);
                   4149: 	$key = &unescape($key);
                   4150: 	next if ($key =~ /^error: 2 /);
                   4151: 	$returnhash{$key}=&thaw_unescape($value);
                   4152:     }
                   4153:     return %returnhash;
1.407     www      4154: }
                   4155: 
1.717     albertel 4156: # --------------------------------------------------------- dumpstore interface
                   4157: 
                   4158: sub dumpstore {
                   4159:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4160:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4161:    if (!$uname) { $uname=$env{'user.name'}; }
                   4162:    my $uhome=&homeserver($uname,$udomain);
                   4163:    if ($regexp) {
                   4164:        $regexp=&escape($regexp);
                   4165:    } else {
                   4166:        $regexp='.';
                   4167:    }
                   4168:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4169:    my @pairs=split(/\&/,$rep);
                   4170:    my %returnhash=();
                   4171:    foreach my $item (@pairs) {
                   4172:        my ($key,$value)=split(/=/,$item,2);
                   4173:        next if ($key =~ /^error: 2 /);
                   4174:        $returnhash{$key}=&thaw_unescape($value);
                   4175:    }
                   4176:    return %returnhash;
1.717     albertel 4177: }
                   4178: 
1.407     www      4179: # -------------------------------------------------------------- keys interface
                   4180: 
                   4181: sub getkeys {
                   4182:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4183:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4184:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4185:    my $uhome=&homeserver($uname,$udomain);
                   4186:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4187:    my @keyarray=();
1.800     albertel 4188:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4189:       next if ($key =~ /^error: 2 /);
1.800     albertel 4190:       push(@keyarray,&unescape($key));
1.407     www      4191:    }
                   4192:    return @keyarray;
1.318     matthew  4193: }
                   4194: 
1.319     matthew  4195: # --------------------------------------------------------------- currentdump
                   4196: sub currentdump {
1.328     matthew  4197:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4198:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4199:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4200:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4201:    my $uhome = &homeserver($sname,$sdom);
                   4202:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4203:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4204:    #
1.318     matthew  4205:    my %returnhash=();
1.319     matthew  4206:    #
                   4207:    if ($rep eq "unknown_cmd") { 
                   4208:        # an old lond will not know currentdump
                   4209:        # Do a dump and make it look like a currentdump
1.822     albertel 4210:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4211:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4212:        my %hash = @tmp;
                   4213:        @tmp=();
1.424     matthew  4214:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4215:    } else {
                   4216:        my @pairs=split(/\&/,$rep);
1.800     albertel 4217:        foreach my $pair (@pairs) {
                   4218:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4219:            my ($symb,$param) = split(/:/,$key);
                   4220:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4221:                                                         &thaw_unescape($value);
1.319     matthew  4222:        }
1.191     harris41 4223:    }
1.12      www      4224:    return %returnhash;
1.424     matthew  4225: }
                   4226: 
                   4227: sub convert_dump_to_currentdump{
                   4228:     my %hash = %{shift()};
                   4229:     my %returnhash;
                   4230:     # Code ripped from lond, essentially.  The only difference
                   4231:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4232:     # we might run in to problems with parameter names =~ /^v\./
                   4233:     while (my ($key,$value) = each(%hash)) {
                   4234:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4235: 	$symb  = &unescape($symb);
                   4236: 	$param = &unescape($param);
1.424     matthew  4237:         next if ($v eq 'version' || $symb eq 'keys');
                   4238:         next if (exists($returnhash{$symb}) &&
                   4239:                  exists($returnhash{$symb}->{$param}) &&
                   4240:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4241:         $returnhash{$symb}->{$param}=$value;
                   4242:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4243:     }
                   4244:     #
                   4245:     # Remove all of the keys in the hashes which keep track of
                   4246:     # the version of the parameter.
                   4247:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4248:         # use a foreach because we are going to delete from the hash.
                   4249:         foreach my $key (keys(%$param_hash)) {
                   4250:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4251:         }
                   4252:     }
                   4253:     return \%returnhash;
1.12      www      4254: }
                   4255: 
1.627     albertel 4256: # ------------------------------------------------------ critical inc interface
                   4257: 
                   4258: sub cinc {
                   4259:     return &inc(@_,'critical');
                   4260: }
                   4261: 
1.449     matthew  4262: # --------------------------------------------------------------- inc interface
                   4263: 
                   4264: sub inc {
1.627     albertel 4265:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4266:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4267:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4268:     my $uhome=&homeserver($uname,$udomain);
                   4269:     my $items='';
                   4270:     if (! ref($store)) {
                   4271:         # got a single value, so use that instead
                   4272:         $items = &escape($store).'=&';
                   4273:     } elsif (ref($store) eq 'SCALAR') {
                   4274:         $items = &escape($$store).'=&';        
                   4275:     } elsif (ref($store) eq 'ARRAY') {
                   4276:         $items = join('=&',map {&escape($_);} @{$store});
                   4277:     } elsif (ref($store) eq 'HASH') {
                   4278:         while (my($key,$value) = each(%{$store})) {
                   4279:             $items.= &escape($key).'='.&escape($value).'&';
                   4280:         }
                   4281:     }
                   4282:     $items=~s/\&$//;
1.627     albertel 4283:     if ($critical) {
                   4284: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4285:     } else {
                   4286: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4287:     }
1.449     matthew  4288: }
                   4289: 
1.12      www      4290: # --------------------------------------------------------------- put interface
                   4291: 
                   4292: sub put {
1.134     albertel 4293:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4294:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4295:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4296:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4297:    my $items='';
1.800     albertel 4298:    foreach my $item (keys(%$storehash)) {
                   4299:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4300:    }
1.12      www      4301:    $items=~s/\&$//;
1.134     albertel 4302:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4303: }
                   4304: 
1.631     albertel 4305: # ------------------------------------------------------------ newput interface
                   4306: 
                   4307: sub newput {
                   4308:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4309:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4310:    if (!$uname) { $uname=$env{'user.name'}; }
                   4311:    my $uhome=&homeserver($uname,$udomain);
                   4312:    my $items='';
                   4313:    foreach my $key (keys(%$storehash)) {
                   4314:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4315:    }
                   4316:    $items=~s/\&$//;
                   4317:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4318: }
                   4319: 
                   4320: # ---------------------------------------------------------  putstore interface
                   4321: 
1.524     raeburn  4322: sub putstore {
1.715     albertel 4323:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4324:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4325:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4326:    my $uhome=&homeserver($uname,$udomain);
                   4327:    my $items='';
1.715     albertel 4328:    foreach my $key (keys(%$storehash)) {
                   4329:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4330:    }
1.715     albertel 4331:    $items=~s/\&$//;
1.716     albertel 4332:    my $esc_symb=&escape($symb);
                   4333:    my $esc_v=&escape($version);
1.715     albertel 4334:    my $reply =
1.716     albertel 4335:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4336: 	      $uhome);
                   4337:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4338:        # gfall back to way things use to be done
1.715     albertel 4339:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4340: 			    $uname);
1.524     raeburn  4341:    }
1.715     albertel 4342:    return $reply;
                   4343: }
                   4344: 
                   4345: sub old_putstore {
1.716     albertel 4346:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4347:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4348:     if (!$uname) { $uname=$env{'user.name'}; }
                   4349:     my $uhome=&homeserver($uname,$udomain);
                   4350:     my %newstorehash;
1.800     albertel 4351:     foreach my $item (keys(%$storehash)) {
                   4352: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4353: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4354:     }
                   4355:     my $items='';
                   4356:     my %allitems = ();
1.800     albertel 4357:     foreach my $item (keys(%newstorehash)) {
                   4358: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4359: 	    my $key = $1.':keys:'.$2;
                   4360: 	    $allitems{$key} .= $3.':';
                   4361: 	}
1.800     albertel 4362: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4363:     }
1.800     albertel 4364:     foreach my $item (keys(%allitems)) {
                   4365: 	$allitems{$item} =~ s/\:$//;
                   4366: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4367:     }
                   4368:     $items=~s/\&$//;
                   4369:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4370: }
                   4371: 
1.47      www      4372: # ------------------------------------------------------ critical put interface
                   4373: 
                   4374: sub cput {
1.134     albertel 4375:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4376:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4377:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4378:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4379:    my $items='';
1.800     albertel 4380:    foreach my $item (keys(%$storehash)) {
                   4381:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4382:    }
1.47      www      4383:    $items=~s/\&$//;
1.134     albertel 4384:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4385: }
                   4386: 
                   4387: # -------------------------------------------------------------- eget interface
                   4388: 
                   4389: sub eget {
1.133     albertel 4390:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4391:    my $items='';
1.800     albertel 4392:    foreach my $item (@$storearr) {
                   4393:        $items.=&escape($item).'&';
1.191     harris41 4394:    }
1.12      www      4395:    $items=~s/\&$//;
1.620     albertel 4396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4397:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4398:    my $uhome=&homeserver($uname,$udomain);
                   4399:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4400:    my @pairs=split(/\&/,$rep);
                   4401:    my %returnhash=();
1.42      www      4402:    my $i=0;
1.800     albertel 4403:    foreach my $item (@$storearr) {
                   4404:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4405:       $i++;
1.191     harris41 4406:    }
1.12      www      4407:    return %returnhash;
                   4408: }
                   4409: 
1.667     albertel 4410: # ------------------------------------------------------------ tmpput interface
                   4411: sub tmpput {
1.802     raeburn  4412:     my ($storehash,$server,$context)=@_;
1.667     albertel 4413:     my $items='';
1.800     albertel 4414:     foreach my $item (keys(%$storehash)) {
                   4415: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4416:     }
                   4417:     $items=~s/\&$//;
1.802     raeburn  4418:     if (defined($context)) {
                   4419:         $items .= ':'.&escape($context);
                   4420:     }
1.667     albertel 4421:     return &reply("tmpput:$items",$server);
                   4422: }
                   4423: 
                   4424: # ------------------------------------------------------------ tmpget interface
                   4425: sub tmpget {
1.688     albertel 4426:     my ($token,$server)=@_;
                   4427:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4428:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4429:     my %returnhash;
                   4430:     foreach my $item (split(/\&/,$rep)) {
                   4431: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4432:         next if ($key =~ /^error: 2 /);
1.667     albertel 4433: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4434:     }
                   4435:     return %returnhash;
                   4436: }
                   4437: 
1.688     albertel 4438: # ------------------------------------------------------------ tmpget interface
                   4439: sub tmpdel {
                   4440:     my ($token,$server)=@_;
                   4441:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4442:     return &reply("tmpdel:$token",$server);
                   4443: }
                   4444: 
1.765     albertel 4445: # -------------------------------------------------- portfolio access checking
                   4446: 
                   4447: sub portfolio_access {
1.766     albertel 4448:     my ($requrl) = @_;
1.765     albertel 4449:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4450:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4451:     if ($result) {
                   4452:         my %setters;
                   4453:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4454:             my ($startblock,$endblock) =
                   4455:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4456:             if ($startblock && $endblock) {
                   4457:                 return 'B';
                   4458:             }
                   4459:         } else {
                   4460:             my ($startblock,$endblock) =
                   4461:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4462:             if ($startblock && $endblock) {
                   4463:                 return 'B';
                   4464:             }
                   4465:         }
                   4466:     }
1.765     albertel 4467:     if ($result eq 'ok') {
1.766     albertel 4468:        return 'F';
1.765     albertel 4469:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4470:        return 'A';
1.765     albertel 4471:     }
1.766     albertel 4472:     return '';
1.765     albertel 4473: }
                   4474: 
                   4475: sub get_portfolio_access {
1.767     albertel 4476:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4477: 
                   4478:     if (!ref($access_hash)) {
                   4479: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4480: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4481: 						   $file_name);
                   4482: 	$access_hash = $access_controls{$file_name};
                   4483:     }
                   4484: 
1.765     albertel 4485:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4486:     my $now = time;
                   4487:     if (ref($access_hash) eq 'HASH') {
                   4488:         foreach my $key (keys(%{$access_hash})) {
                   4489:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4490:             if ($start > $now) {
                   4491:                 next;
                   4492:             }
                   4493:             if ($end && $end<$now) {
                   4494:                 next;
                   4495:             }
                   4496:             if ($scope eq 'public') {
                   4497:                 $public = $key;
                   4498:                 last;
                   4499:             } elsif ($scope eq 'guest') {
                   4500:                 $guest = $key;
                   4501:             } elsif ($scope eq 'domains') {
                   4502:                 push(@domains,$key);
                   4503:             } elsif ($scope eq 'users') {
                   4504:                 push(@users,$key);
                   4505:             } elsif ($scope eq 'course') {
                   4506:                 push(@courses,$key);
                   4507:             } elsif ($scope eq 'group') {
                   4508:                 push(@groups,$key);
                   4509:             }
                   4510:         }
                   4511:         if ($public) {
                   4512:             return 'ok';
                   4513:         }
                   4514:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4515:             if ($guest) {
                   4516:                 return $guest;
                   4517:             }
                   4518:         } else {
                   4519:             if (@domains > 0) {
                   4520:                 foreach my $domkey (@domains) {
                   4521:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4522:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4523:                             return 'ok';
                   4524:                         }
                   4525:                     }
                   4526:                 }
                   4527:             }
                   4528:             if (@users > 0) {
                   4529:                 foreach my $userkey (@users) {
1.865     raeburn  4530:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4531:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4532:                             if (ref($item) eq 'HASH') {
                   4533:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4534:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4535:                                     return 'ok';
                   4536:                                 }
                   4537:                             }
                   4538:                         }
                   4539:                     } 
1.765     albertel 4540:                 }
                   4541:             }
                   4542:             my %roleshash;
                   4543:             my @courses_and_groups = @courses;
                   4544:             push(@courses_and_groups,@groups); 
                   4545:             if (@courses_and_groups > 0) {
                   4546:                 my (%allgroups,%allroles); 
                   4547:                 my ($start,$end,$role,$sec,$group);
                   4548:                 foreach my $envkey (%env) {
1.811     albertel 4549:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4550:                         my $cid = $2.'_'.$3; 
                   4551:                         if ($1 eq 'gr') {
                   4552:                             $group = $4;
                   4553:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4554:                         } else {
                   4555:                             if ($4 eq '') {
                   4556:                                 $sec = 'none';
                   4557:                             } else {
                   4558:                                 $sec = $4;
                   4559:                             }
                   4560:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4561:                         }
1.811     albertel 4562:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4563:                         my $cid = $2.'_'.$3;
                   4564:                         if ($4 eq '') {
                   4565:                             $sec = 'none';
                   4566:                         } else {
                   4567:                             $sec = $4;
                   4568:                         }
                   4569:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4570:                     }
                   4571:                 }
                   4572:                 if (keys(%allroles) == 0) {
                   4573:                     return;
                   4574:                 }
                   4575:                 foreach my $key (@courses_and_groups) {
                   4576:                     my %content = %{$$access_hash{$key}};
                   4577:                     my $cnum = $content{'number'};
                   4578:                     my $cdom = $content{'domain'};
                   4579:                     my $cid = $cdom.'_'.$cnum;
                   4580:                     if (!exists($allroles{$cid})) {
                   4581:                         next;
                   4582:                     }    
                   4583:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4584:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4585:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4586:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4587:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4588:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4589:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4590:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4591:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4592:                                         if (grep/^all$/,@sections) {
                   4593:                                             return 'ok';
                   4594:                                         } else {
                   4595:                                             if (grep/^$sec$/,@sections) {
                   4596:                                                 return 'ok';
                   4597:                                             }
                   4598:                                         }
                   4599:                                     }
                   4600:                                 }
                   4601:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4602:                                     if (grep/^none$/,@groups) {
                   4603:                                         return 'ok';
                   4604:                                     }
                   4605:                                 } else {
                   4606:                                     if (grep/^all$/,@groups) {
                   4607:                                         return 'ok';
                   4608:                                     } 
                   4609:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4610:                                         if (grep/^$group$/,@groups) {
                   4611:                                             return 'ok';
                   4612:                                         }
                   4613:                                     }
                   4614:                                 } 
                   4615:                             }
                   4616:                         }
                   4617:                     }
                   4618:                 }
                   4619:             }
                   4620:             if ($guest) {
                   4621:                 return $guest;
                   4622:             }
                   4623:         }
                   4624:     }
                   4625:     return;
                   4626: }
                   4627: 
                   4628: sub course_group_datechecker {
                   4629:     my ($dates,$now,$status) = @_;
                   4630:     my ($start,$end) = split(/\./,$dates);
                   4631:     if (!$start && !$end) {
                   4632:         return 'ok';
                   4633:     }
                   4634:     if (grep/^active$/,@{$status}) {
                   4635:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4636:             return 'ok';
                   4637:         }
                   4638:     }
                   4639:     if (grep/^previous$/,@{$status}) {
                   4640:         if ($end > $now ) {
                   4641:             return 'ok';
                   4642:         }
                   4643:     }
                   4644:     if (grep/^future$/,@{$status}) {
                   4645:         if ($start > $now) {
                   4646:             return 'ok';
                   4647:         }
                   4648:     }
                   4649:     return; 
                   4650: }
                   4651: 
                   4652: sub parse_portfolio_url {
                   4653:     my ($url) = @_;
                   4654: 
                   4655:     my ($type,$udom,$unum,$group,$file_name);
                   4656:     
1.823     albertel 4657:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4658: 	$type = 1;
                   4659:         $udom = $1;
                   4660:         $unum = $2;
                   4661:         $file_name = $3;
1.823     albertel 4662:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4663: 	$type = 2;
                   4664:         $udom = $1;
                   4665:         $unum = $2;
                   4666:         $group = $3;
                   4667:         $file_name = $3.'/'.$4;
                   4668:     }
                   4669:     if (wantarray) {
                   4670: 	return ($type,$udom,$unum,$file_name,$group);
                   4671:     }
                   4672:     return $type;
                   4673: }
                   4674: 
                   4675: sub is_portfolio_url {
                   4676:     my ($url) = @_;
                   4677:     return scalar(&parse_portfolio_url($url));
                   4678: }
                   4679: 
1.798     raeburn  4680: sub is_portfolio_file {
                   4681:     my ($file) = @_;
1.820     raeburn  4682:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4683:         return 1;
                   4684:     }
                   4685:     return;
                   4686: }
                   4687: 
1.976     raeburn  4688: sub usertools_access {
1.985     raeburn  4689:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4690:     my ($access,%tools);
                   4691:     if ($context eq '') {
                   4692:         $context = 'tools';
                   4693:     }
                   4694:     if ($context eq 'requestcourses') {
                   4695:         %tools = (
                   4696:                       official   => 1,
                   4697:                       unofficial => 1,
1.1006    raeburn  4698:                       community  => 1,
1.985     raeburn  4699:                  );
                   4700:     } else {
                   4701:         %tools = (
                   4702:                       aboutme   => 1,
                   4703:                       blog      => 1,
                   4704:                       portfolio => 1,
                   4705:                  );
                   4706:     }
1.976     raeburn  4707:     return if (!defined($tools{$tool}));
                   4708: 
                   4709:     if ((!defined($udom)) || (!defined($uname))) {
                   4710:         $udom = $env{'user.domain'};
                   4711:         $uname = $env{'user.name'};
                   4712:     }
                   4713: 
1.978     raeburn  4714:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4715:         if ($action ne 'reload') {
1.985     raeburn  4716:             if ($context eq 'requestcourses') {
                   4717:                 return $env{'environment.canrequest.'.$tool};
                   4718:             } else {
                   4719:                 return $env{'environment.availabletools.'.$tool};
                   4720:             }
                   4721:         }
1.976     raeburn  4722:     }
                   4723: 
                   4724:     my ($toolstatus,$inststatus);
                   4725: 
1.985     raeburn  4726:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4727:          ($action ne 'reload')) {
                   4728:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4729:         $inststatus = $env{'environment.inststatus'};
                   4730:     } else {
1.1025  ! raeburn  4731:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4732:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4733:         $inststatus = $userenv{'inststatus'};
                   4734:     }
                   4735: 
                   4736:     if ($toolstatus ne '') {
                   4737:         if ($toolstatus) {
                   4738:             $access = 1;
                   4739:         } else {
                   4740:             $access = 0;
                   4741:         }
                   4742:         return $access;
                   4743:     }
                   4744: 
                   4745:     my $is_adv = &is_advanced_user($udom,$uname);
                   4746:     my %domdef = &get_domain_defaults($udom);
                   4747:     if (ref($domdef{$tool}) eq 'HASH') {
                   4748:         if ($is_adv) {
                   4749:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4750:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4751:                     $access = 1;
                   4752:                 } else {
                   4753:                     $access = 0;
                   4754:                 }
                   4755:                 return $access;
                   4756:             }
                   4757:         }
                   4758:         if ($inststatus ne '') {
                   4759:             my ($hasaccess,$hasnoaccess);
                   4760:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4761:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4762:                     if ($domdef{$tool}{$affiliation}) {
                   4763:                         $hasaccess = 1;
                   4764:                     } else {
                   4765:                         $hasnoaccess = 1;
                   4766:                     }
                   4767:                 }
                   4768:             }
                   4769:             if ($hasaccess || $hasnoaccess) {
                   4770:                 if ($hasaccess) {
                   4771:                     $access = 1;
                   4772:                 } elsif ($hasnoaccess) {
                   4773:                     $access = 0; 
                   4774:                 }
                   4775:                 return $access;
                   4776:             }
                   4777:         } else {
                   4778:             if ($domdef{$tool}{'default'} ne '') {
                   4779:                 if ($domdef{$tool}{'default'}) {
                   4780:                     $access = 1;
                   4781:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4782:                     $access = 0;
                   4783:                 }
                   4784:                 return $access;
                   4785:             }
                   4786:         }
                   4787:     } else {
1.985     raeburn  4788:         if ($context eq 'tools') {
                   4789:             $access = 1;
                   4790:         } else {
                   4791:             $access = 0;
                   4792:         }
1.976     raeburn  4793:         return $access;
                   4794:     }
                   4795: }
                   4796: 
                   4797: sub is_advanced_user {
                   4798:     my ($udom,$uname) = @_;
                   4799:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4800:     my %allroles;
                   4801:     my $is_adv;
                   4802:     foreach my $role (keys(%roleshash)) {
                   4803:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4804:         my $area = '/'.$tdomain.'/'.$trest;
                   4805:         if ($sec ne '') {
                   4806:             $area .= '/'.$sec;
                   4807:         }
                   4808:         if (($area ne '') && ($trole ne '')) {
                   4809:             my $spec=$trole.'.'.$area;
                   4810:             if ($trole =~ /^cr\//) {
                   4811:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4812:             } elsif ($trole ne 'gr') {
                   4813:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4814:             }
                   4815:         }
                   4816:     }
                   4817:     foreach my $role (keys(%allroles)) {
                   4818:         last if ($is_adv);
                   4819:         foreach my $item (split(/:/,$allroles{$role})) {
                   4820:             if ($item ne '') {
                   4821:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4822:                 if ($privilege eq 'adv') {
                   4823:                     $is_adv = 1;
                   4824:                     last;
                   4825:                 }
                   4826:             }
                   4827:         }
                   4828:     }
                   4829:     return $is_adv;
                   4830: }
1.798     raeburn  4831: 
1.341     www      4832: # ---------------------------------------------- Custom access rule evaluation
                   4833: 
                   4834: sub customaccess {
                   4835:     my ($priv,$uri)=@_;
1.807     albertel 4836:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4837:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4838:     $udom = &LONCAPA::clean_domain($udom);
                   4839:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4840:     my $access=0;
1.800     albertel 4841:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4842: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4843: 	if ($type eq 'user') {
                   4844: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4845: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4846: 		if ($tdom) {
                   4847: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4848: 		}
1.896     albertel 4849: 		if ($tuname) {
                   4850: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4851: 		}
                   4852: 		$access=($effect eq 'allow');
                   4853: 		last;
                   4854: 	    }
                   4855: 	} else {
                   4856: 	    if ($role) {
                   4857: 		if ($role ne $urole) { next; }
                   4858: 	    }
                   4859: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4860: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4861: 		if ($tdom) {
                   4862: 		    if ($tdom ne $udom) { next; }
                   4863: 		}
                   4864: 		if ($tcrs) {
                   4865: 		    if ($tcrs ne $ucrs) { next; }
                   4866: 		}
                   4867: 		if ($tsec) {
                   4868: 		    if ($tsec ne $usec) { next; }
                   4869: 		}
                   4870: 		$access=($effect eq 'allow');
                   4871: 		last;
                   4872: 	    }
                   4873: 	    if ($realm eq '' && $role eq '') {
                   4874: 		$access=($effect eq 'allow');
                   4875: 	    }
1.402     bowersj2 4876: 	}
1.341     www      4877:     }
                   4878:     return $access;
                   4879: }
                   4880: 
1.103     harris41 4881: # ------------------------------------------------- Check for a user privilege
1.12      www      4882: 
                   4883: sub allowed {
1.810     raeburn  4884:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4885:     my $ver_orguri=$uri;
1.439     www      4886:     $uri=&deversion($uri);
1.152     www      4887:     my $orguri=$uri;
1.52      www      4888:     $uri=&declutter($uri);
1.809     raeburn  4889: 
1.810     raeburn  4890:     if ($priv eq 'evb') {
                   4891: # Evade communication block restrictions for specified role in a course
                   4892:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4893:             return $1;
                   4894:         } else {
                   4895:             return;
                   4896:         }
                   4897:     }
                   4898: 
1.620     albertel 4899:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4900: # Free bre access to adm and meta resources
1.775     albertel 4901:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4902: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4903: 	&& ($priv eq 'bre')) {
1.14      www      4904: 	return 'F';
1.159     www      4905:     }
                   4906: 
1.545     banghart 4907: # Free bre access to user's own portfolio contents
1.714     raeburn  4908:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4909:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4910: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4911:         my %setters;
                   4912:         my ($startblock,$endblock) = 
                   4913:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4914:         if ($startblock && $endblock) {
                   4915:             return 'B';
                   4916:         } else {
                   4917:             return 'F';
                   4918:         }
1.545     banghart 4919:     }
                   4920: 
1.762     raeburn  4921: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4922:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4923:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4924:         if (exists($env{'request.course.id'})) {
                   4925:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4926:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4927:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4928:                 my $courseprivid=$env{'request.course.id'};
                   4929:                 $courseprivid=~s/\_/\//;
                   4930:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4931:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4932:                     return $1; 
1.762     raeburn  4933:                 } else {
                   4934:                     if ($env{'request.course.sec'}) {
                   4935:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4936:                     }
                   4937:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4938:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4939:                         return $2;
                   4940:                     }
1.714     raeburn  4941:                 }
                   4942:             }
                   4943:         }
                   4944:     }
                   4945: 
1.159     www      4946: # Free bre to public access
                   4947: 
                   4948:     if ($priv eq 'bre') {
1.238     www      4949:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4950: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4951:            return 'F'; 
                   4952:         }
1.238     www      4953:         if ($copyright eq 'priv') {
                   4954:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4955: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4956: 		return '';
                   4957:             }
                   4958:         }
                   4959:         if ($copyright eq 'domain') {
                   4960:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4961: 	    unless (($env{'user.domain'} eq $1) ||
                   4962:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4963: 		return '';
                   4964:             }
1.262     matthew  4965:         }
1.620     albertel 4966:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4967:             # Library role, so allow browsing of resources in this domain.
                   4968:             return 'F';
1.238     www      4969:         }
1.341     www      4970:         if ($copyright eq 'custom') {
                   4971: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4972:         }
1.14      www      4973:     }
1.264     matthew  4974:     # Domain coordinator is trying to create a course
1.620     albertel 4975:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4976:         # uri is the requested domain in this case.
                   4977:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4978:         # a role of dc for the domain in question.
1.620     albertel 4979:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4980:     }
1.29      www      4981: 
1.52      www      4982:     my $thisallowed='';
                   4983:     my $statecond=0;
                   4984:     my $courseprivid='';
                   4985: 
                   4986: # Course
                   4987: 
1.620     albertel 4988:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4989:        $thisallowed.=$1;
                   4990:     }
1.29      www      4991: 
1.52      www      4992: # Domain
                   4993: 
1.620     albertel 4994:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4995:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4996:        $thisallowed.=$1;
                   4997:     }
1.52      www      4998: 
                   4999: # Course: uri itself is a course
1.66      www      5000:     my $courseuri=$uri;
                   5001:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5002:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5003: 
1.620     albertel 5004:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5005:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      5006:        $thisallowed.=$1;
                   5007:     }
1.29      www      5008: 
1.665     albertel 5009: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5010: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5011:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5012: 	$thisallowed='';
1.671     raeburn  5013:         my ($match)=&is_on_map($uri);
                   5014:         if ($match) {
                   5015:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5016:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5017:                 $thisallowed.=$1;
                   5018:             }
                   5019:         } else {
1.705     albertel 5020:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5021:             if ($refuri) {
                   5022:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5023:                     $thisallowed='F';
1.671     raeburn  5024:                 } else {
                   5025:                     $refuri=&declutter($refuri);
                   5026:                     my ($match) = &is_on_map($refuri);
                   5027:                     if ($match) {
                   5028:                         $thisallowed='F';
                   5029:                     }
1.669     raeburn  5030:                 }
1.671     raeburn  5031:             }
                   5032:         }
1.314     www      5033:     }
1.492     albertel 5034: 
1.766     albertel 5035:     if ($priv eq 'bre'
                   5036: 	&& $thisallowed ne 'F' 
                   5037: 	&& $thisallowed ne '2'
                   5038: 	&& &is_portfolio_url($uri)) {
                   5039: 	$thisallowed = &portfolio_access($uri);
                   5040:     }
                   5041:     
1.52      www      5042: # Full access at system, domain or course-wide level? Exit.
1.29      www      5043:     if ($thisallowed=~/F/) {
                   5044: 	return 'F';
                   5045:     }
                   5046: 
1.52      www      5047: # If this is generating or modifying users, exit with special codes
1.29      www      5048: 
1.643     www      5049:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5050: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5051: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5052: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5053: 	    unless ($auname) { return $thisallowed; }
                   5054: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5055: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5056: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5057: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5058: 	}
1.52      www      5059: 	return $thisallowed;
                   5060:     }
                   5061: #
1.103     harris41 5062: # Gathered so far: system, domain and course wide privileges
1.52      www      5063: #
                   5064: # Course: See if uri or referer is an individual resource that is part of 
                   5065: # the course
                   5066: 
1.620     albertel 5067:     if ($env{'request.course.id'}) {
1.232     www      5068: 
1.620     albertel 5069:        $courseprivid=$env{'request.course.id'};
                   5070:        if ($env{'request.course.sec'}) {
                   5071:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5072:        }
                   5073:        $courseprivid=~s/\_/\//;
                   5074:        my $checkreferer=1;
1.232     www      5075:        my ($match,$cond)=&is_on_map($uri);
                   5076:        if ($match) {
                   5077:            $statecond=$cond;
1.620     albertel 5078:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5079:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5080:                $thisallowed.=$1;
                   5081:                $checkreferer=0;
                   5082:            }
1.29      www      5083:        }
1.83      www      5084:        
1.148     www      5085:        if ($checkreferer) {
1.620     albertel 5086: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5087:             unless ($refuri) {
1.800     albertel 5088:                 foreach my $key (keys(%env)) {
                   5089: 		    if ($key=~/^httpref\..*\*/) {
                   5090: 			my $pattern=$key;
1.156     www      5091:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5092:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5093:                         $pattern=~s/\//\\\//g;
1.152     www      5094:                         if ($orguri=~/$pattern/) {
1.800     albertel 5095: 			    $refuri=$env{$key};
1.148     www      5096:                         }
                   5097:                     }
1.191     harris41 5098:                 }
1.148     www      5099:             }
1.232     www      5100: 
1.148     www      5101:          if ($refuri) { 
1.152     www      5102: 	  $refuri=&declutter($refuri);
1.232     www      5103:           my ($match,$cond)=&is_on_map($refuri);
                   5104:             if ($match) {
                   5105:               my $refstatecond=$cond;
1.620     albertel 5106:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5107:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5108:                   $thisallowed.=$1;
1.53      www      5109:                   $uri=$refuri;
                   5110:                   $statecond=$refstatecond;
1.52      www      5111:               }
                   5112:           }
1.148     www      5113:         }
1.29      www      5114:        }
1.52      www      5115:    }
1.29      www      5116: 
1.52      www      5117: #
1.103     harris41 5118: # Gathered now: all privileges that could apply, and condition number
1.52      www      5119: # 
                   5120: #
                   5121: # Full or no access?
                   5122: #
1.29      www      5123: 
1.52      www      5124:     if ($thisallowed=~/F/) {
                   5125: 	return 'F';
                   5126:     }
1.29      www      5127: 
1.52      www      5128:     unless ($thisallowed) {
                   5129:         return '';
                   5130:     }
1.29      www      5131: 
1.52      www      5132: # Restrictions exist, deal with them
                   5133: #
                   5134: #   C:according to course preferences
                   5135: #   R:according to resource settings
                   5136: #   L:unless locked
                   5137: #   X:according to user session state
                   5138: #
                   5139: 
                   5140: # Possibly locked functionality, check all courses
1.54      www      5141: # Locks might take effect only after 10 minutes cache expiration for other
                   5142: # courses, and 2 minutes for current course
1.52      www      5143: 
                   5144:     my $envkey;
                   5145:     if ($thisallowed=~/L/) {
1.1000    raeburn  5146:         foreach $envkey (keys(%env)) {
1.54      www      5147:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5148:                my $courseid=$2;
                   5149:                my $roleid=$1.'.'.$2;
1.92      www      5150:                $courseid=~s/^\///;
1.54      www      5151:                my $expiretime=600;
1.620     albertel 5152:                if ($env{'request.role'} eq $roleid) {
1.54      www      5153: 		  $expiretime=120;
                   5154:                }
                   5155: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5156:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5157:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5158: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5159:                }
1.620     albertel 5160:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5161:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5162: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5163:                        &log($env{'user.domain'},$env{'user.name'},
                   5164:                             $env{'user.home'},
1.57      www      5165:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5166:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5167:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5168: 		       return '';
                   5169:                    }
                   5170:                }
1.620     albertel 5171:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5172:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5173: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5174:                        &log($env{'user.domain'},$env{'user.name'},
                   5175:                             $env{'user.home'},
1.57      www      5176:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5177:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5178:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5179: 		       return '';
                   5180:                    }
                   5181:                }
                   5182: 	   }
1.29      www      5183:        }
1.52      www      5184:     }
                   5185:    
                   5186: #
                   5187: # Rest of the restrictions depend on selected course
                   5188: #
                   5189: 
1.620     albertel 5190:     unless ($env{'request.course.id'}) {
1.766     albertel 5191: 	if ($thisallowed eq 'A') {
                   5192: 	    return 'A';
1.814     raeburn  5193:         } elsif ($thisallowed eq 'B') {
                   5194:             return 'B';
1.766     albertel 5195: 	} else {
                   5196: 	    return '1';
                   5197: 	}
1.52      www      5198:     }
1.29      www      5199: 
1.52      www      5200: #
                   5201: # Now user is definitely in a course
                   5202: #
1.53      www      5203: 
                   5204: 
                   5205: # Course preferences
                   5206: 
                   5207:    if ($thisallowed=~/C/) {
1.620     albertel 5208:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5209:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5210:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5211: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5212: 	   if ($priv ne 'pch') { 
                   5213: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5214: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5215: 			$env{'request.course.id'});
                   5216: 	   }
1.237     www      5217:            return '';
                   5218:        }
                   5219: 
1.620     albertel 5220:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5221: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5222: 	   if ($priv ne 'pch') { 
                   5223: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5224: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5225: 			$env{'request.course.id'});
                   5226: 	   }
1.54      www      5227:            return '';
                   5228:        }
1.53      www      5229:    }
                   5230: 
                   5231: # Resource preferences
                   5232: 
                   5233:    if ($thisallowed=~/R/) {
1.620     albertel 5234:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5235:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5236: 	   if ($priv ne 'pch') { 
                   5237: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5238: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5239: 	   }
                   5240: 	   return '';
1.54      www      5241:        }
1.53      www      5242:    }
1.30      www      5243: 
1.246     www      5244: # Restricted by state or randomout?
1.30      www      5245: 
1.52      www      5246:    if ($thisallowed=~/X/) {
1.620     albertel 5247:       if ($env{'acc.randomout'}) {
1.579     albertel 5248: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5249:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5250:             return ''; 
                   5251:          }
1.247     www      5252:       }
                   5253:       if (&condval($statecond)) {
1.52      www      5254: 	 return '2';
                   5255:       } else {
                   5256:          return '';
                   5257:       }
                   5258:    }
1.30      www      5259: 
1.766     albertel 5260:     if ($thisallowed eq 'A') {
                   5261: 	return 'A';
1.814     raeburn  5262:     } elsif ($thisallowed eq 'B') {
                   5263:         return 'B';
1.766     albertel 5264:     }
1.52      www      5265:    return 'F';
1.232     www      5266: }
                   5267: 
1.710     albertel 5268: sub split_uri_for_cond {
                   5269:     my $uri=&deversion(&declutter(shift));
                   5270:     my @uriparts=split(/\//,$uri);
                   5271:     my $filename=pop(@uriparts);
                   5272:     my $pathname=join('/',@uriparts);
                   5273:     return ($pathname,$filename);
                   5274: }
1.232     www      5275: # --------------------------------------------------- Is a resource on the map?
                   5276: 
                   5277: sub is_on_map {
1.710     albertel 5278:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5279:     #Trying to find the conditional for the file
1.620     albertel 5280:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5281: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5282:     if ($match) {
1.289     bowersj2 5283: 	return (1,$1);
                   5284:     } else {
1.434     www      5285: 	return (0,0);
1.289     bowersj2 5286:     }
1.12      www      5287: }
                   5288: 
1.427     www      5289: # --------------------------------------------------------- Get symb from alias
                   5290: 
                   5291: sub get_symb_from_alias {
                   5292:     my $symb=shift;
                   5293:     my ($map,$resid,$url)=&decode_symb($symb);
                   5294: # Already is a symb
                   5295:     if ($url) { return $symb; }
                   5296: # Must be an alias
                   5297:     my $aliassymb='';
                   5298:     my %bighash;
1.620     albertel 5299:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5300:                             &GDBM_READER(),0640)) {
                   5301:         my $rid=$bighash{'mapalias_'.$symb};
                   5302: 	if ($rid) {
                   5303: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5304: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5305: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5306: 	}
                   5307:         untie %bighash;
                   5308:     }
                   5309:     return $aliassymb;
                   5310: }
                   5311: 
1.12      www      5312: # ----------------------------------------------------------------- Define Role
                   5313: 
                   5314: sub definerole {
                   5315:   if (allowed('mcr','/')) {
                   5316:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5317:     foreach my $role (split(':',$sysrole)) {
                   5318: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5319:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5320:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5321: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5322:                return "refused:s:$crole&$cqual"; 
                   5323:             }
                   5324:         }
1.191     harris41 5325:     }
1.800     albertel 5326:     foreach my $role (split(':',$domrole)) {
                   5327: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5328:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5329:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5330: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5331:                return "refused:d:$crole&$cqual"; 
                   5332:             }
                   5333:         }
1.191     harris41 5334:     }
1.800     albertel 5335:     foreach my $role (split(':',$courole)) {
                   5336: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5337:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5338:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5339: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5340:                return "refused:c:$crole&$cqual"; 
                   5341:             }
                   5342:         }
1.191     harris41 5343:     }
1.620     albertel 5344:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5345:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5346: 	        "rolesdef_$rolename=".
                   5347:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5348:     return reply($command,$env{'user.home'});
1.12      www      5349:   } else {
                   5350:     return 'refused';
                   5351:   }
1.105     harris41 5352: }
                   5353: 
                   5354: # ---------------- Make a metadata query against the network of library servers
                   5355: 
                   5356: sub metadata_query {
1.244     matthew  5357:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5358:     my %rhash;
1.845     albertel 5359:     my %libserv = &all_library();
1.244     matthew  5360:     my @server_list = (defined($server_array) ? @$server_array
                   5361:                                               : keys(%libserv) );
                   5362:     for my $server (@server_list) {
1.118     harris41 5363: 	unless ($custom or $customshow) {
                   5364: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5365: 	    $rhash{$server}=$reply;
                   5366: 	}
                   5367: 	else {
                   5368: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5369: 			     &escape($custom).':'.&escape($customshow),
                   5370: 			     $server);
                   5371: 	    $rhash{$server}=$reply;
                   5372: 	}
1.112     harris41 5373:     }
1.118     harris41 5374:     return \%rhash;
1.240     www      5375: }
                   5376: 
                   5377: # ----------------------------------------- Send log queries and wait for reply
                   5378: 
                   5379: sub log_query {
                   5380:     my ($uname,$udom,$query,%filters)=@_;
                   5381:     my $uhome=&homeserver($uname,$udom);
                   5382:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5383:     my $uhost=&hostname($uhome);
1.800     albertel 5384:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5385:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5386:                        $uhome);
1.479     albertel 5387:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5388:     return get_query_reply($queryid);
                   5389: }
                   5390: 
1.818     raeburn  5391: # -------------------------- Update MySQL table for portfolio file
                   5392: 
                   5393: sub update_portfolio_table {
1.821     raeburn  5394:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5395:     if ($group ne '') {
                   5396:         $file_name =~s /^\Q$group\E//;
                   5397:     }
1.818     raeburn  5398:     my $homeserver = &homeserver($uname,$udom);
                   5399:     my $queryid=
1.821     raeburn  5400:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5401:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5402:     my $reply = &get_query_reply($queryid);
                   5403:     return $reply;
                   5404: }
                   5405: 
1.899     raeburn  5406: # -------------------------- Update MySQL allusers table
                   5407: 
                   5408: sub update_allusers_table {
                   5409:     my ($uname,$udom,$names) = @_;
                   5410:     my $homeserver = &homeserver($uname,$udom);
                   5411:     my $queryid=
                   5412:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5413:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5414:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5415:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5416:                'generation='.&escape($names->{'generation'}).'%%'.
                   5417:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5418:                'id='.&escape($names->{'id'}),$homeserver);
                   5419:     my $reply = &get_query_reply($queryid);
                   5420:     return $reply;
                   5421: }
                   5422: 
1.508     raeburn  5423: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5424: 
                   5425: sub fetch_enrollment_query {
1.511     raeburn  5426:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5427:     my $homeserver;
1.547     raeburn  5428:     my $maxtries = 1;
1.508     raeburn  5429:     if ($context eq 'automated') {
                   5430:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5431:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5432:     } else {
                   5433:         $homeserver = &homeserver($cnum,$dom);
                   5434:     }
1.838     albertel 5435:     my $host=&hostname($homeserver);
1.506     raeburn  5436:     my $cmd = '';
1.1000    raeburn  5437:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5438:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5439:     }
                   5440:     $cmd =~ s/%%$//;
                   5441:     $cmd = &escape($cmd);
                   5442:     my $query = 'fetchenrollment';
1.620     albertel 5443:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5444:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5445:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5446:         return 'error: '.$queryid;
                   5447:     }
1.506     raeburn  5448:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5449:     my $tries = 1;
                   5450:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5451:         $reply = &get_query_reply($queryid);
                   5452:         $tries ++;
                   5453:     }
1.526     raeburn  5454:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5455:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5456:     } else {
1.901     albertel 5457:         my @responses = split(/:/,$reply);
1.515     raeburn  5458:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5459:             foreach my $line (@responses) {
                   5460:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5461:                 $$replyref{$key} = $value;
                   5462:             }
                   5463:         } else {
1.506     raeburn  5464:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5465:             foreach my $line (@responses) {
                   5466:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5467:                 $$replyref{$key} = $value;
                   5468:                 if ($value > 0) {
1.800     albertel 5469:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5470:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5471:                         my $destname = $pathname.'/'.$filename;
                   5472:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5473:                         if ($xml_classlist =~ /^error/) {
                   5474:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5475:                         } else {
1.506     raeburn  5476:                             if ( open(FILE,">$destname") ) {
                   5477:                                 print FILE &unescape($xml_classlist);
                   5478:                                 close(FILE);
1.526     raeburn  5479:                             } else {
                   5480:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5481:                             }
                   5482:                         }
                   5483:                     }
                   5484:                 }
                   5485:             }
                   5486:         }
                   5487:         return 'ok';
                   5488:     }
                   5489:     return 'error';
                   5490: }
                   5491: 
1.242     www      5492: sub get_query_reply {
                   5493:     my $queryid=shift;
1.240     www      5494:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5495:     my $reply='';
                   5496:     for (1..100) {
                   5497: 	sleep 2;
                   5498:         if (-e $replyfile.'.end') {
1.448     albertel 5499: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5500: 		$reply = join('',<$fh>);
                   5501: 		close($fh);
1.240     www      5502: 	   } else { return 'error: reply_file_error'; }
1.242     www      5503:            return &unescape($reply);
                   5504: 	}
1.240     www      5505:     }
1.242     www      5506:     return 'timeout:'.$queryid;
1.240     www      5507: }
                   5508: 
                   5509: sub courselog_query {
1.241     www      5510: #
                   5511: # possible filters:
                   5512: # url: url or symb
                   5513: # username
                   5514: # domain
                   5515: # action: view, submit, grade
                   5516: # start: timestamp
                   5517: # end: timestamp
                   5518: #
1.240     www      5519:     my (%filters)=@_;
1.620     albertel 5520:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5521:     if ($filters{'url'}) {
                   5522: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5523:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5524:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5525:     }
1.620     albertel 5526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5528:     return &log_query($cname,$cdom,'courselog',%filters);
                   5529: }
                   5530: 
                   5531: sub userlog_query {
1.858     raeburn  5532: #
                   5533: # possible filters:
                   5534: # action: log check role
                   5535: # start: timestamp
                   5536: # end: timestamp
                   5537: #
1.240     www      5538:     my ($uname,$udom,%filters)=@_;
                   5539:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5540: }
                   5541: 
1.506     raeburn  5542: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5543: 
                   5544: sub auto_run {
1.508     raeburn  5545:     my ($cnum,$cdom) = @_;
1.876     raeburn  5546:     my $response = 0;
                   5547:     my $settings;
                   5548:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5549:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5550:         $settings = $domconfig{'autoenroll'};
                   5551:         if ($settings->{'run'} eq '1') {
                   5552:             $response = 1;
                   5553:         }
                   5554:     } else {
1.934     raeburn  5555:         my $homeserver;
                   5556:         if (&is_course($cdom,$cnum)) {
                   5557:             $homeserver = &homeserver($cnum,$cdom);
                   5558:         } else {
                   5559:             $homeserver = &domain($cdom,'primary');
                   5560:         }
                   5561:         if ($homeserver ne 'no_host') {
                   5562:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5563:         }
1.876     raeburn  5564:     }
1.506     raeburn  5565:     return $response;
                   5566: }
1.776     albertel 5567: 
1.506     raeburn  5568: sub auto_get_sections {
1.508     raeburn  5569:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5570:     my $homeserver;
                   5571:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5572:         $homeserver = &homeserver($cnum,$cdom);
                   5573:     }
                   5574:     if (!defined($homeserver)) { 
                   5575:         if ($cdom =~ /^$match_domain$/) {
                   5576:             $homeserver = &domain($cdom,'primary');
                   5577:         }
                   5578:     }
                   5579:     my @secs;
                   5580:     if (defined($homeserver)) {
                   5581:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5582:         unless ($response eq 'refused') {
                   5583:             @secs = split(/:/,$response);
                   5584:         }
1.506     raeburn  5585:     }
                   5586:     return @secs;
                   5587: }
1.776     albertel 5588: 
1.506     raeburn  5589: sub auto_new_course {
1.508     raeburn  5590:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5591:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5592:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5593:     return $response;
                   5594: }
1.776     albertel 5595: 
1.506     raeburn  5596: sub auto_validate_courseID {
1.508     raeburn  5597:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5598:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5599:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5600:     return $response;
                   5601: }
1.776     albertel 5602: 
1.1007    raeburn  5603: sub auto_validate_instcode {
1.1020    raeburn  5604:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5605:     my ($homeserver,$response);
                   5606:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5607:         $homeserver = &homeserver($cnum,$cdom);
                   5608:     }
                   5609:     if (!defined($homeserver)) {
                   5610:         if ($cdom =~ /^$match_domain$/) {
                   5611:             $homeserver = &domain($cdom,'primary');
                   5612:         }
                   5613:     }
                   5614:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020    raeburn  5615:                            &escape($instcode).':'.&escape($owner),$homeserver));
1.1007    raeburn  5616:     return $response;
                   5617: }
                   5618: 
1.506     raeburn  5619: sub auto_create_password {
1.873     raeburn  5620:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5621:     my ($homeserver,$response);
1.506     raeburn  5622:     my $create_passwd = 0;
                   5623:     my $authchk = '';
1.873     raeburn  5624:     if ($udom =~ /^$match_domain$/) {
                   5625:         $homeserver = &domain($udom,'primary');
                   5626:     }
                   5627:     if ($homeserver eq '') {
                   5628:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5629:             $homeserver = &homeserver($cnum,$cdom);
                   5630:         }
                   5631:     }
                   5632:     if ($homeserver eq '') {
                   5633:         $authchk = 'nodomain';
1.506     raeburn  5634:     } else {
1.873     raeburn  5635:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5636:         if ($response eq 'refused') {
                   5637:             $authchk = 'refused';
                   5638:         } else {
1.901     albertel 5639:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5640:         }
1.506     raeburn  5641:     }
                   5642:     return ($authparam,$create_passwd,$authchk);
                   5643: }
                   5644: 
1.706     raeburn  5645: sub auto_photo_permission {
                   5646:     my ($cnum,$cdom,$students) = @_;
                   5647:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5648:     my ($outcome,$perm_reqd,$conditions) = 
                   5649: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5650:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5651: 	return (undef,undef);
                   5652:     }
1.706     raeburn  5653:     return ($outcome,$perm_reqd,$conditions);
                   5654: }
                   5655: 
                   5656: sub auto_checkphotos {
                   5657:     my ($uname,$udom,$pid) = @_;
                   5658:     my $homeserver = &homeserver($uname,$udom);
                   5659:     my ($result,$resulttype);
                   5660:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5661: 				   &escape($uname).':'.&escape($pid),
                   5662: 				   $homeserver));
1.709     albertel 5663:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5664: 	return (undef,undef);
                   5665:     }
1.706     raeburn  5666:     if ($outcome) {
                   5667:         ($result,$resulttype) = split(/:/,$outcome);
                   5668:     } 
                   5669:     return ($result,$resulttype);
                   5670: }
                   5671: 
                   5672: sub auto_photochoice {
                   5673:     my ($cnum,$cdom) = @_;
                   5674:     my $homeserver = &homeserver($cnum,$cdom);
                   5675:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5676: 						       &escape($cdom),
                   5677: 						       $homeserver)));
1.709     albertel 5678:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5679: 	return (undef,undef);
                   5680:     }
1.706     raeburn  5681:     return ($update,$comment);
                   5682: }
                   5683: 
                   5684: sub auto_photoupdate {
                   5685:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5686:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5687:     my $host=&hostname($homeserver);
1.706     raeburn  5688:     my $cmd = '';
                   5689:     my $maxtries = 1;
1.800     albertel 5690:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5691:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5692:     }
                   5693:     $cmd =~ s/%%$//;
                   5694:     $cmd = &escape($cmd);
                   5695:     my $query = 'institutionalphotos';
                   5696:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5697:     unless ($queryid=~/^\Q$host\E\_/) {
                   5698:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5699:         return 'error: '.$queryid;
                   5700:     }
                   5701:     my $reply = &get_query_reply($queryid);
                   5702:     my $tries = 1;
                   5703:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5704:         $reply = &get_query_reply($queryid);
                   5705:         $tries ++;
                   5706:     }
                   5707:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5708:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5709:     } else {
                   5710:         my @responses = split(/:/,$reply);
                   5711:         my $outcome = shift(@responses); 
                   5712:         foreach my $item (@responses) {
                   5713:             my ($key,$value) = split(/=/,$item);
                   5714:             $$photo{$key} = $value;
                   5715:         }
                   5716:         return $outcome;
                   5717:     }
                   5718:     return 'error';
                   5719: }
                   5720: 
1.521     raeburn  5721: sub auto_instcode_format {
1.793     albertel 5722:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5723: 	$cat_order) = @_;
1.521     raeburn  5724:     my $courses = '';
1.772     raeburn  5725:     my @homeservers;
1.521     raeburn  5726:     if ($caller eq 'global') {
1.841     albertel 5727: 	my %servers = &get_servers($codedom,'library');
                   5728: 	foreach my $tryserver (keys(%servers)) {
                   5729: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5730: 		push(@homeservers,$tryserver);
                   5731: 	    }
1.584     raeburn  5732:         }
1.1022    raeburn  5733:     } elsif ($caller eq 'requests') {
                   5734:         if ($codedom =~ /^$match_domain$/) {
                   5735:             my $chome = &domain($codedom,'primary');
                   5736:             unless ($chome eq 'no_host') {
                   5737:                 push(@homeservers,$chome);
                   5738:             }
                   5739:         }
1.521     raeburn  5740:     } else {
1.772     raeburn  5741:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5742:     }
1.793     albertel 5743:     foreach my $code (keys(%{$instcodes})) {
                   5744:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5745:     }
                   5746:     chop($courses);
1.772     raeburn  5747:     my $ok_response = 0;
                   5748:     my $response;
                   5749:     while (@homeservers > 0 && $ok_response == 0) {
                   5750:         my $server = shift(@homeservers); 
                   5751:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5752:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5753:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5754: 		split(/:/,$response);
1.772     raeburn  5755:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5756:             push(@{$codetitles},&str2array($codetitles_str));
                   5757:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5758:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5759:             $ok_response = 1;
                   5760:         }
                   5761:     }
                   5762:     if ($ok_response) {
1.521     raeburn  5763:         return 'ok';
1.772     raeburn  5764:     } else {
                   5765:         return $response;
1.521     raeburn  5766:     }
                   5767: }
                   5768: 
1.792     raeburn  5769: sub auto_instcode_defaults {
                   5770:     my ($domain,$returnhash,$code_order) = @_;
                   5771:     my @homeservers;
1.841     albertel 5772: 
                   5773:     my %servers = &get_servers($domain,'library');
                   5774:     foreach my $tryserver (keys(%servers)) {
                   5775: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5776: 	    push(@homeservers,$tryserver);
                   5777: 	}
1.792     raeburn  5778:     }
1.841     albertel 5779: 
1.792     raeburn  5780:     my $response;
1.841     albertel 5781:     foreach my $server (@homeservers) {
1.792     raeburn  5782:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5783:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5784: 	
                   5785: 	foreach my $pair (split(/\&/,$response)) {
                   5786: 	    my ($name,$value)=split(/\=/,$pair);
                   5787: 	    if ($name eq 'code_order') {
                   5788: 		@{$code_order} = split(/\&/,&unescape($value));
                   5789: 	    } else {
                   5790: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5791: 	    }
                   5792: 	}
                   5793: 	return 'ok';
1.792     raeburn  5794:     }
1.841     albertel 5795: 
                   5796:     return $response;
1.1003    raeburn  5797: }
                   5798: 
                   5799: sub auto_possible_instcodes {
1.1007    raeburn  5800:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5801:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5802:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5803:         return;
                   5804:     }
1.1003    raeburn  5805:     my (@homeservers,$uhome);
                   5806:     if (defined(&domain($domain,'primary'))) {
                   5807:         $uhome=&domain($domain,'primary');
                   5808:         push(@homeservers,&domain($domain,'primary'));
                   5809:     } else {
                   5810:         my %servers = &get_servers($domain,'library');
                   5811:         foreach my $tryserver (keys(%servers)) {
                   5812:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5813:                 push(@homeservers,$tryserver);
                   5814:             }
                   5815:         }
                   5816:     }
                   5817:     my $response;
                   5818:     foreach my $server (@homeservers) {
                   5819:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5820:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5821:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5822:             split(':',$response);
                   5823:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5824:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5825:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5826:             my ($name,$value)=split('=',$item);
                   5827:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5828:         }
                   5829:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5830:             my ($name,$value)=split('=',$item);
                   5831:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5832:         }
                   5833:         return 'ok';
                   5834:     }
                   5835:     return $response;
                   5836: }
1.792     raeburn  5837: 
1.1010    raeburn  5838: sub auto_courserequest_checks {
                   5839:     my ($dom) = @_;
1.1020    raeburn  5840:     my ($homeserver,%validations);
                   5841:     if ($dom =~ /^$match_domain$/) {
                   5842:         $homeserver = &domain($dom,'primary');
                   5843:     }
                   5844:     unless ($homeserver eq 'no_host') {
                   5845:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   5846:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   5847:             my @items = split(/&/,$response);
                   5848:             foreach my $item (@items) {
                   5849:                 my ($key,$value) = split('=',$item);
                   5850:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   5851:             }
                   5852:         }
                   5853:     }
1.1010    raeburn  5854:     return %validations; 
                   5855: }
                   5856: 
1.1020    raeburn  5857: sub auto_courserequest_validation {
                   5858:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   5859:     my ($homeserver,$response);
                   5860:     if ($dom =~ /^$match_domain$/) {
                   5861:         $homeserver = &domain($dom,'primary');
                   5862:     }
                   5863:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  5864:           
1.1020    raeburn  5865:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  5866:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  5867:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   5868:                                     $homeserver));
                   5869:     }
                   5870:     return $response;
                   5871: }
                   5872: 
1.777     albertel 5873: sub auto_validate_class_sec {
1.918     raeburn  5874:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5875:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5876:     my $ownerlist;
                   5877:     if (ref($owners) eq 'ARRAY') {
                   5878:         $ownerlist = join(',',@{$owners});
                   5879:     } else {
                   5880:         $ownerlist = $owners;
                   5881:     }
1.773     raeburn  5882:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5883:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5884:     return $response;
                   5885: }
                   5886: 
1.679     raeburn  5887: # ------------------------------------------------------- Course Group routines
                   5888: 
                   5889: sub get_coursegroups {
1.809     raeburn  5890:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5891:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5892: }
                   5893: 
1.679     raeburn  5894: sub modify_coursegroup {
                   5895:     my ($cdom,$cnum,$groupsettings) = @_;
                   5896:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5897: }
                   5898: 
1.809     raeburn  5899: sub toggle_coursegroup_status {
                   5900:     my ($cdom,$cnum,$group,$action) = @_;
                   5901:     my ($from_namespace,$to_namespace);
                   5902:     if ($action eq 'delete') {
                   5903:         $from_namespace = 'coursegroups';
                   5904:         $to_namespace = 'deleted_groups';
                   5905:     } else {
                   5906:         $from_namespace = 'deleted_groups';
                   5907:         $to_namespace = 'coursegroups';
                   5908:     }
                   5909:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5910:     if (my $tmp = &error(%curr_group)) {
                   5911:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5912:         return ('read error',$tmp);
                   5913:     } else {
                   5914:         my %savedsettings = %curr_group; 
1.809     raeburn  5915:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5916:         my $deloutcome;
                   5917:         if ($result eq 'ok') {
1.809     raeburn  5918:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5919:         } else {
                   5920:             return ('write error',$result);
                   5921:         }
                   5922:         if ($deloutcome eq 'ok') {
                   5923:             return 'ok';
                   5924:         } else {
                   5925:             return ('delete error',$deloutcome);
                   5926:         }
                   5927:     }
                   5928: }
                   5929: 
1.679     raeburn  5930: sub modify_group_roles {
1.957     raeburn  5931:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5932:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5933:     my $role = 'gr/'.&escape($userprivs);
                   5934:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5935:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5936:     if ($result eq 'ok') {
                   5937:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5938:     }
1.679     raeburn  5939:     return $result;
                   5940: }
                   5941: 
                   5942: sub modify_coursegroup_membership {
                   5943:     my ($cdom,$cnum,$membership) = @_;
                   5944:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5945:     return $result;
                   5946: }
                   5947: 
1.682     raeburn  5948: sub get_active_groups {
                   5949:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5950:     my $now = time;
                   5951:     my %groups = ();
                   5952:     foreach my $key (keys(%env)) {
1.811     albertel 5953:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5954:             my ($start,$end) = split(/\./,$env{$key});
                   5955:             if (($end!=0) && ($end<$now)) { next; }
                   5956:             if (($start!=0) && ($start>$now)) { next; }
                   5957:             if ($1 eq $cdom && $2 eq $cnum) {
                   5958:                 $groups{$3} = $env{$key} ;
                   5959:             }
                   5960:         }
                   5961:     }
                   5962:     return %groups;
                   5963: }
                   5964: 
1.683     raeburn  5965: sub get_group_membership {
                   5966:     my ($cdom,$cnum,$group) = @_;
                   5967:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5968: }
                   5969: 
                   5970: sub get_users_groups {
                   5971:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5972:     my @usersgroups;
1.683     raeburn  5973:     my $cachetime=1800;
                   5974: 
                   5975:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5976:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5977:     if (defined($cached)) {
1.734     albertel 5978:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5979:     } else {  
                   5980:         $grouplist = '';
1.816     raeburn  5981:         my $courseurl = &courseid_to_courseurl($courseid);
                   5982:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5983:         my $access_end = $env{'course.'.$courseid.
                   5984:                               '.default_enrollment_end_date'};
                   5985:         my $now = time;
                   5986:         foreach my $key (keys(%roleshash)) {
                   5987:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5988:                 my $group = $1;
                   5989:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5990:                     my $start = $2;
                   5991:                     my $end = $1;
                   5992:                     if ($start == -1) { next; } # deleted from group
                   5993:                     if (($start!=0) && ($start>$now)) { next; }
                   5994:                     if (($end!=0) && ($end<$now)) {
                   5995:                         if ($access_end && $access_end < $now) {
                   5996:                             if ($access_end - $end < 86400) {
                   5997:                                 push(@usersgroups,$group);
1.733     raeburn  5998:                             }
                   5999:                         }
1.817     raeburn  6000:                         next;
1.733     raeburn  6001:                     }
1.817     raeburn  6002:                     push(@usersgroups,$group);
1.683     raeburn  6003:                 }
                   6004:             }
                   6005:         }
1.817     raeburn  6006:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6007:         $grouplist = join(':',@usersgroups);
                   6008:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6009:     }
1.733     raeburn  6010:     return @usersgroups;
1.683     raeburn  6011: }
                   6012: 
                   6013: sub devalidate_getgroups_cache {
                   6014:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6015:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6016: 
1.683     raeburn  6017:     my $hashid="$udom:$uname:$courseid";
                   6018:     &devalidate_cache_new('getgroups',$hashid);
                   6019: }
                   6020: 
1.12      www      6021: # ------------------------------------------------------------------ Plain Text
                   6022: 
                   6023: sub plaintext {
1.988     raeburn  6024:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 6025:     if ($short =~ /^cr/) {
                   6026: 	return (split('/',$short))[-1];
                   6027:     }
1.742     raeburn  6028:     if (!defined($cid)) {
                   6029:         $cid = $env{'request.course.id'};
                   6030:     }
1.988     raeburn  6031:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
                   6032:         unless ($forcedefault) {
                   6033:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6034:             &Apache::lonlocal::mt_escape(\$roletext);
                   6035:             return &Apache::lonlocal::mt($roletext);
                   6036:         }
1.742     raeburn  6037:     }
                   6038:     my %rolenames = (
1.1008    raeburn  6039:                       Course    => 'std',
                   6040:                       Community => 'alt1',
1.742     raeburn  6041:                     );
                   6042:     if (defined($type) && 
                   6043:          defined($rolenames{$type}) && 
                   6044:          defined($prp{$short}{$rolenames{$type}})) {
                   6045:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   6046:     } else {
                   6047:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   6048:     }
1.12      www      6049: }
                   6050: 
                   6051: # ----------------------------------------------------------------- Assign Role
                   6052: 
                   6053: sub assignrole {
1.957     raeburn  6054:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6055:         $context)=@_;
1.21      www      6056:     my $mrole;
                   6057:     if ($role =~ /^cr\//) {
1.393     www      6058:         my $cwosec=$url;
1.811     albertel 6059:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6060: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      6061:            &logthis('Refused custom assignrole: '.
                   6062:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 6063: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      6064:            return 'refused'; 
                   6065:         }
1.21      www      6066:         $mrole='cr';
1.678     raeburn  6067:     } elsif ($role =~ /^gr\//) {
                   6068:         my $cwogrp=$url;
1.811     albertel 6069:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6070:         unless (&allowed('mdg',$cwogrp)) {
                   6071:             &logthis('Refused group assignrole: '.
                   6072:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6073:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6074:             return 'refused';
                   6075:         }
                   6076:         $mrole='gr';
1.21      www      6077:     } else {
1.82      www      6078:         my $cwosec=$url;
1.811     albertel 6079:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6080:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6081:             my $refused;
                   6082:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6083:                 if (!(&allowed('c'.$role,$url))) {
                   6084:                     $refused = 1;
                   6085:                 }
                   6086:             } else {
                   6087:                 $refused = 1;
                   6088:             }
1.947     raeburn  6089:             if ($refused) {
                   6090:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6091:                     $refused = '';
1.1017    raeburn  6092:                 } elsif ($context eq 'requestcourses') {
                   6093:                     if (($role eq 'cc') && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
                   6094:                         my ($cdom,$cnum) = ($cwosec =~ m{^/($match_domain)/($match_courseid)$});
                   6095:                         my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6096:                         if ($crsenv{'internal.courseowner'} eq 
                   6097:                              $env{'user.name'}.':'.$env{'user.domain'}) {
                   6098:                             $refused = '';
                   6099:                         }
                   6100:                     }
                   6101:                 }
                   6102:                 if ($refused) {
1.947     raeburn  6103:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6104:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6105: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6106:                     return 'refused';
                   6107:                 }
1.932     raeburn  6108:             }
1.104     www      6109:         }
1.21      www      6110:         $mrole=$role;
                   6111:     }
1.620     albertel 6112:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6113:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6114:     if ($end) { $command.='_'.$end; }
1.21      www      6115:     if ($start) {
                   6116: 	if ($end) { 
1.81      www      6117:            $command.='_'.$start; 
1.21      www      6118:         } else {
1.81      www      6119:            $command.='_0_'.$start;
1.21      www      6120:         }
                   6121:     }
1.739     raeburn  6122:     my $origstart = $start;
                   6123:     my $origend = $end;
1.957     raeburn  6124:     my $delflag;
1.357     www      6125: # actually delete
                   6126:     if ($deleteflag) {
1.373     www      6127: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6128: # modify command to delete the role
1.620     albertel 6129:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6130:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6131: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6132: # set start and finish to negative values for userrolelog
                   6133:            $start=-1;
                   6134:            $end=-1;
1.957     raeburn  6135:            $delflag = 1;
1.357     www      6136:         }
                   6137:     }
                   6138: # send command
1.349     www      6139:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6140: # log new user role if status is ok
1.349     www      6141:     if ($answer eq 'ok') {
1.663     raeburn  6142: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6143: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6144:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6145:         unless ($role =~ /^gr/) {
                   6146:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6147:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6148:         }
1.349     www      6149:     }
                   6150:     return $answer;
1.169     harris41 6151: }
                   6152: 
                   6153: # -------------------------------------------------- Modify user authentication
1.197     www      6154: # Overrides without validation
                   6155: 
1.169     harris41 6156: sub modifyuserauth {
                   6157:     my ($udom,$uname,$umode,$upass)=@_;
                   6158:     my $uhome=&homeserver($uname,$udom);
1.197     www      6159:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6160:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6161:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6162:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6163:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6164: 		     &escape($upass),$uhome);
1.620     albertel 6165:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6166:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6167:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6168:     &log($udom,,$uname,$uhome,
1.620     albertel 6169:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6170:                                      $env{'user.name'}.', '.$umode.
1.197     www      6171:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6172:     unless ($reply eq 'ok') {
1.197     www      6173:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6174: 	return 'error: '.$reply;
                   6175:     }   
1.170     harris41 6176:     return 'ok';
1.80      www      6177: }
                   6178: 
1.81      www      6179: # --------------------------------------------------------------- Modify a user
1.80      www      6180: 
1.81      www      6181: sub modifyuser {
1.206     matthew  6182:     my ($udom,    $uname, $uid,
                   6183:         $umode,   $upass, $first,
                   6184:         $middle,  $last,  $gene,
1.963     raeburn  6185:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6186:     $udom= &LONCAPA::clean_domain($udom);
                   6187:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6188:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6189:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6190: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6191:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6192:                                      ' desiredhome not specified'). 
1.620     albertel 6193:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6194:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6195:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6196: # ----------------------------------------------------------------- Create User
1.406     albertel 6197:     if (($uhome eq 'no_host') && 
                   6198: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6199:         my $unhome='';
1.844     albertel 6200:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6201:             $unhome = $desiredhome;
1.620     albertel 6202: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6203: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6204:         } else { # load balancing routine for determining $unhome
1.81      www      6205:             my $loadm=10000000;
1.841     albertel 6206: 	    my %servers = &get_servers($udom,'library');
                   6207: 	    foreach my $tryserver (keys(%servers)) {
                   6208: 		my $answer=reply('load',$tryserver);
                   6209: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6210: 		    $loadm=$answer;
                   6211: 		    $unhome=$tryserver;
                   6212: 		}
1.80      www      6213: 	    }
                   6214:         }
                   6215:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6216: 	    return 'error: unable to find a home server for '.$uname.
                   6217:                    ' in domain '.$udom;
1.80      www      6218:         }
                   6219:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6220:                          &escape($upass),$unhome);
                   6221: 	unless ($reply eq 'ok') {
                   6222:             return 'error: '.$reply;
                   6223:         }   
1.230     stredwic 6224:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6225:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6226: 	    return 'error: unable verify users home machine.';
1.80      www      6227:         }
1.209     matthew  6228:     }   # End of creation of new user
1.80      www      6229: # ---------------------------------------------------------------------- Add ID
                   6230:     if ($uid) {
                   6231:        $uid=~tr/A-Z/a-z/;
                   6232:        my %uidhash=&idrget($udom,$uname);
1.196     www      6233:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6234:          && (!$forceid)) {
1.80      www      6235: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6236: 	      return 'error: user id "'.$uid.'" does not match '.
                   6237:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6238:           }
                   6239:        } else {
                   6240: 	  &idput($udom,($uname => $uid));
                   6241:        }
                   6242:     }
                   6243: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6244:     my @tmp=&get('environment',
1.899     raeburn  6245: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6246:                     'permanentemail','inststatus'],
1.134     albertel 6247: 		   $udom,$uname);
1.313     matthew  6248:     my %names;
                   6249:     if ($tmp[0] =~ m/^error:.*/) { 
                   6250:         %names=(); 
                   6251:     } else {
                   6252:         %names = @tmp;
                   6253:     }
1.388     www      6254: #
                   6255: # Make sure to not trash student environment if instructor does not bother
                   6256: # to supply name and email information
                   6257: #
                   6258:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6259:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6260:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6261:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6262:     if ($email) {
                   6263:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6264:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6265:     }
1.899     raeburn  6266:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6267:     if (defined($inststatus)) {
                   6268:         $names{'inststatus'} = '';
                   6269:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6270:         if (ref($usertypes) eq 'HASH') {
                   6271:             my @okstatuses; 
                   6272:             foreach my $item (split(/:/,$inststatus)) {
                   6273:                 if (defined($usertypes->{$item})) {
                   6274:                     push(@okstatuses,$item);  
                   6275:                 }
                   6276:             }
                   6277:             if (@okstatuses) {
                   6278:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6279:             }
                   6280:         }
                   6281:     }
1.134     albertel 6282:     my $reply = &put('environment', \%names, $udom,$uname);
                   6283:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6284:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6285:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6286:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6287:                  $umode.', '.$first.', '.$middle.', '.
                   6288: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6289:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6290:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6291:     } else {
                   6292:         $logmsg .= ' during self creation';
                   6293:     }
                   6294:     &logthis($logmsg);
1.134     albertel 6295:     return 'ok';
1.80      www      6296: }
                   6297: 
1.81      www      6298: # -------------------------------------------------------------- Modify student
1.80      www      6299: 
1.81      www      6300: sub modifystudent {
                   6301:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6302:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6303:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6304:     if (!$cid) {
1.620     albertel 6305: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6306: 	    return 'not_in_class';
                   6307: 	}
1.80      www      6308:     }
                   6309: # --------------------------------------------------------------- Make the user
1.81      www      6310:     my $reply=&modifyuser
1.209     matthew  6311: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6312:          $desiredhome,$email,$inststatus);
1.80      www      6313:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6314:     # This will cause &modify_student_enrollment to get the uid from the
                   6315:     # students environment
                   6316:     $uid = undef if (!$forceid);
1.455     albertel 6317:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6318: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6319:     return $reply;
                   6320: }
                   6321: 
                   6322: sub modify_student_enrollment {
1.957     raeburn  6323:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6324:     my ($cdom,$cnum,$chome);
                   6325:     if (!$cid) {
1.620     albertel 6326: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6327: 	    return 'not_in_class';
                   6328: 	}
1.620     albertel 6329: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6330: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6331:     } else {
                   6332: 	($cdom,$cnum)=split(/_/,$cid);
                   6333:     }
1.620     albertel 6334:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6335:     if (!$chome) {
1.457     raeburn  6336: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6337:     }
1.455     albertel 6338:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6339:     # Make sure the user exists
1.81      www      6340:     my $uhome=&homeserver($uname,$udom);
                   6341:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6342: 	return 'error: no such user';
                   6343:     }
1.297     matthew  6344:     # Get student data if we were not given enough information
                   6345:     if (!defined($first)  || $first  eq '' || 
                   6346:         !defined($last)   || $last   eq '' || 
                   6347:         !defined($uid)    || $uid    eq '' || 
                   6348:         !defined($middle) || $middle eq '' || 
                   6349:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6350:         # They did not supply us with enough data to enroll the student, so
                   6351:         # we need to pick up more information.
1.297     matthew  6352:         my %tmp = &get('environment',
1.294     matthew  6353:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6354:                        ,$udom,$uname);
                   6355: 
1.800     albertel 6356:         #foreach my $key (keys(%tmp)) {
                   6357:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6358:         #}
1.294     matthew  6359:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6360:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6361:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6362:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6363:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6364:     }
1.556     albertel 6365:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6366:     my $reply=cput('classlist',
                   6367: 		   {"$uname:$udom" => 
1.515     raeburn  6368: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6369: 		   $cdom,$cnum);
1.81      www      6370:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6371: 	return 'error: '.$reply;
1.652     albertel 6372:     } else {
                   6373: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6374:     }
1.297     matthew  6375:     # Add student role to user
1.83      www      6376:     my $uurl='/'.$cid;
1.81      www      6377:     $uurl=~s/\_/\//g;
                   6378:     if ($usec) {
                   6379: 	$uurl.='/'.$usec;
                   6380:     }
1.957     raeburn  6381:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6382: }
                   6383: 
1.556     albertel 6384: sub format_name {
                   6385:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6386:     my $name;
                   6387:     if ($first ne 'lastname') {
                   6388: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6389:     } else {
                   6390: 	if ($lastname=~/\S/) {
                   6391: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6392: 	    $name=~s/\s+,/,/;
                   6393: 	} else {
                   6394: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6395: 	}
                   6396:     }
                   6397:     $name=~s/^\s+//;
                   6398:     $name=~s/\s+$//;
                   6399:     $name=~s/\s+/ /g;
                   6400:     return $name;
                   6401: }
                   6402: 
1.84      www      6403: # ------------------------------------------------- Write to course preferences
                   6404: 
                   6405: sub writecoursepref {
                   6406:     my ($courseid,%prefs)=@_;
                   6407:     $courseid=~s/^\///;
                   6408:     $courseid=~s/\_/\//g;
                   6409:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6410:     my $chome=homeserver($cnum,$cdomain);
                   6411:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6412: 	return 'error: no such course';
                   6413:     }
                   6414:     my $cstring='';
1.800     albertel 6415:     foreach my $pref (keys(%prefs)) {
                   6416: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6417:     }
1.84      www      6418:     $cstring=~s/\&$//;
                   6419:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6420: }
                   6421: 
                   6422: # ---------------------------------------------------------- Make/modify course
                   6423: 
                   6424: sub createcourse {
1.741     raeburn  6425:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6426:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6427:     $url=&declutter($url);
                   6428:     my $cid='';
1.264     matthew  6429:     unless (&allowed('ccc',$udom)) {
1.1017    raeburn  6430:         if ($context eq 'requestcourses') {
                   6431:             unless (&usertools_access($course_owner,$udom,$category,undef,$context)) {
                   6432:                 return 'refused';
                   6433:             }
                   6434:         } else {
                   6435:             return 'refused';
                   6436:         }
1.84      www      6437:     }
1.1011    raeburn  6438: # --------------------------------------------------------------- Get Unique ID
                   6439:     my $uname;
                   6440:     if ($cnum =~ /^$match_courseid$/) {
                   6441:         my $chome=&homeserver($cnum,$udom,'true');
                   6442:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6443:             $uname = $cnum;
                   6444:         } else {
                   6445:             $uname = &generate_coursenum($udom);
                   6446:         }
                   6447:     } else {
                   6448:         $uname = &generate_coursenum($udom);
                   6449:     }
                   6450:     return $uname if ($uname =~ /^error/);
                   6451: # -------------------------------------------------- Check supplied server name
1.620     albertel 6452:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6453:     if (! &is_library($course_server)) {
1.264     matthew  6454:         return 'error:bad server name '.$course_server;
                   6455:     }
1.84      www      6456: # ------------------------------------------------------------- Make the course
                   6457:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6458:                       $course_server);
1.84      www      6459:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6460:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6461:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6462: 	return 'error: no such course';
                   6463:     }
1.271     www      6464: # ----------------------------------------------------------------- Course made
1.516     raeburn  6465: # log existence
1.918     raeburn  6466:     my $newcourse = {
                   6467:                     $udom.'_'.$uname => {
1.921     raeburn  6468:                                      description => $description,
                   6469:                                      inst_code   => $inst_code,
                   6470:                                      owner       => $course_owner,
                   6471:                                      type        => $crstype,
1.918     raeburn  6472:                                                 },
                   6473:                     };
1.921     raeburn  6474:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6475: # set toplevel url
1.271     www      6476:     my $topurl=$url;
                   6477:     unless ($nonstandard) {
                   6478: # ------------------------------------------ For standard courses, make top url
                   6479:         my $mapurl=&clutter($url);
1.278     www      6480:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6481:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6482: <map>
                   6483: <resource id="1" type="start"></resource>
                   6484: <resource id="2" src="$mapurl"></resource>
                   6485: <resource id="3" type="finish"></resource>
                   6486: <link index="1" from="1" to="2"></link>
                   6487: <link index="2" from="2" to="3"></link>
                   6488: </map>
                   6489: ENDINITMAP
                   6490:         $topurl=&declutter(
1.638     albertel 6491:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6492:                           );
                   6493:     }
                   6494: # ----------------------------------------------------------- Write preferences
1.84      www      6495:     &writecoursepref($udom.'_'.$uname,
                   6496:                      ('description' => $description,
1.271     www      6497:                       'url'         => $topurl));
1.84      www      6498:     return '/'.$udom.'/'.$uname;
                   6499: }
                   6500: 
1.1011    raeburn  6501: # ------------------------------------------------------------------- Create ID
                   6502: sub generate_coursenum {
                   6503:     my ($udom) = @_;
                   6504:     my $domdesc = &domain($udom);
                   6505:     return 'error: invalid domain' if ($domdesc eq '');
                   6506:     my $uname=int(1+rand(9)).
                   6507:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6508:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6509:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6510: # ----------------------------------------------- Make sure that does not exist
                   6511:     my $uhome=&homeserver($uname,$udom,'true');
                   6512:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6513:         $uname=int(1+rand(9)).
                   6514:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6515:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6516:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6517:         $uhome=&homeserver($uname,$udom,'true');
                   6518:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6519:             return 'error: unable to generate unique course-ID';
                   6520:         }
                   6521:     }
                   6522:     return $uname;
                   6523: }
                   6524: 
1.813     albertel 6525: sub is_course {
                   6526:     my ($cdom,$cnum) = @_;
                   6527:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6528: 				undef,'.');
1.813     albertel 6529:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6530:         return 1;
                   6531:     }
                   6532:     return 0;
                   6533: }
                   6534: 
1.1015    raeburn  6535: sub store_userdata {
                   6536:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  6537:     my $result;
1.1016    raeburn  6538:     if ($datakey ne '') {
1.1013    raeburn  6539:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  6540:             if ($udom eq '' || $uname eq '') {
                   6541:                 $udom = $env{'user.domain'};
                   6542:                 $uname = $env{'user.name'};
                   6543:             }
                   6544:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  6545:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   6546:                 $result = 'error: no_host';
                   6547:             } else {
                   6548:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   6549:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   6550: 
                   6551:                 my $namevalue='';
                   6552:                 foreach my $key (keys(%{$storehash})) {
                   6553:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6554:                 }
                   6555:                 $namevalue=~s/\&$//;
                   6556:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  6557:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  6558:             }
                   6559:         } else {
                   6560:             $result = 'error: data to store was not a hash reference'; 
                   6561:         }
                   6562:     } else {
                   6563:         $result= 'error: invalid requestkey'; 
                   6564:     }
                   6565:     return $result;
                   6566: }
                   6567: 
1.21      www      6568: # ---------------------------------------------------------- Assign Custom Role
                   6569: 
                   6570: sub assigncustomrole {
1.957     raeburn  6571:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6572:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6573:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6574: }
                   6575: 
                   6576: # ----------------------------------------------------------------- Revoke Role
                   6577: 
                   6578: sub revokerole {
1.957     raeburn  6579:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6580:     my $now=time;
1.965     raeburn  6581:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6582: }
                   6583: 
                   6584: # ---------------------------------------------------------- Revoke Custom Role
                   6585: 
                   6586: sub revokecustomrole {
1.957     raeburn  6587:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6588:     my $now=time;
1.357     www      6589:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6590:            $deleteflag,$selfenroll,$context);
1.17      www      6591: }
                   6592: 
1.533     banghart 6593: # ------------------------------------------------------------ Disk usage
1.535     albertel 6594: sub diskusage {
1.955     raeburn  6595:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6596:     $directorypath =~ s/\/$//;
                   6597:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6598:                        .&escape($getpropath).':'.&escape($uname).':'
                   6599:                        .&escape($udom),homeserver($uname,$udom));
                   6600:     if ($listing eq 'unknown_cmd') {
                   6601:         if ($getpropath) {
                   6602:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6603:         }
                   6604:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6605:     }
1.514     albertel 6606:     return $listing;
1.512     banghart 6607: }
                   6608: 
1.566     banghart 6609: sub is_locked {
                   6610:     my ($file_name, $domain, $user) = @_;
                   6611:     my @check;
                   6612:     my $is_locked;
                   6613:     push @check, $file_name;
1.613     albertel 6614:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6615: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6616:     my ($tmp)=keys(%locked);
                   6617:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6618:     
1.566     banghart 6619:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6620:         $is_locked = 'false';
                   6621:         foreach my $entry (@{$locked{$file_name}}) {
                   6622:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6623:                $is_locked = 'true';
                   6624:                last;
1.745     raeburn  6625:            }
                   6626:        }
1.566     banghart 6627:     } else {
                   6628:         $is_locked = 'false';
                   6629:     }
                   6630: }
                   6631: 
1.759     albertel 6632: sub declutter_portfile {
                   6633:     my ($file) = @_;
1.833     albertel 6634:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6635:     return $file;
                   6636: }
                   6637: 
1.559     banghart 6638: # ------------------------------------------------------------- Mark as Read Only
                   6639: 
                   6640: sub mark_as_readonly {
                   6641:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6642:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6643:     my ($tmp)=keys(%current_permissions);
                   6644:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6645:     foreach my $file (@{$files}) {
1.759     albertel 6646: 	$file = &declutter_portfile($file);
1.561     banghart 6647:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6648:     }
1.613     albertel 6649:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6650:     return;
                   6651: }
                   6652: 
1.572     banghart 6653: # ------------------------------------------------------------Save Selected Files
                   6654: 
                   6655: sub save_selected_files {
                   6656:     my ($user, $path, @files) = @_;
                   6657:     my $filename = $user."savedfiles";
1.573     banghart 6658:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6659:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6660:     foreach my $file (@files) {
1.620     albertel 6661:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6662:     }
                   6663:     foreach my $file (@other_files) {
1.574     banghart 6664:         print (OUT $file."\n");
1.572     banghart 6665:     }
1.574     banghart 6666:     close (OUT);
1.572     banghart 6667:     return 'ok';
                   6668: }
                   6669: 
1.574     banghart 6670: sub clear_selected_files {
                   6671:     my ($user) = @_;
                   6672:     my $filename = $user."savedfiles";
                   6673:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6674:     print (OUT undef);
                   6675:     close (OUT);
                   6676:     return ("ok");    
                   6677: }
                   6678: 
1.572     banghart 6679: sub files_in_path {
                   6680:     my ($user, $path) = @_;
                   6681:     my $filename = $user."savedfiles";
                   6682:     my %return_files;
1.574     banghart 6683:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6684:     while (my $line_in = <IN>) {
1.574     banghart 6685:         chomp ($line_in);
                   6686:         my @paths_and_file = split (m!/!, $line_in);
                   6687:         my $file_part = pop (@paths_and_file);
                   6688:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6689:         $path_part.='/';
                   6690:         my $path_and_file = $path_part.$file_part;
                   6691:         if ($path_part eq $path) {
                   6692:             $return_files{$file_part}= 'selected';
                   6693:         }
                   6694:     }
1.574     banghart 6695:     close (IN);
                   6696:     return (\%return_files);
1.572     banghart 6697: }
                   6698: 
                   6699: # called in portfolio select mode, to show files selected NOT in current directory
                   6700: sub files_not_in_path {
                   6701:     my ($user, $path) = @_;
                   6702:     my $filename = $user."savedfiles";
                   6703:     my @return_files;
                   6704:     my $path_part;
1.800     albertel 6705:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6706:     while (my $line = <IN>) {
1.572     banghart 6707:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6708:         my @paths_and_file = split(m|/|, $line);
                   6709:         my $file_part = pop(@paths_and_file);
                   6710:         chomp($file_part);
                   6711:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6712:         $path_part .= '/';
                   6713:         my $path_and_file = $path_part.$file_part;
                   6714:         if ($path_part ne $path) {
1.800     albertel 6715:             push(@return_files, ($path_and_file));
1.572     banghart 6716:         }
                   6717:     }
1.800     albertel 6718:     close(OUT);
1.574     banghart 6719:     return (@return_files);
1.572     banghart 6720: }
                   6721: 
1.745     raeburn  6722: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6723: 
1.745     raeburn  6724: sub get_portfile_permissions {
                   6725:     my ($domain,$user) = @_;
1.613     albertel 6726:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6727:     my ($tmp)=keys(%current_permissions);
                   6728:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6729:     return \%current_permissions;
                   6730: }
                   6731: 
                   6732: #---------------------------------------------Get portfolio file access controls
                   6733: 
1.749     raeburn  6734: sub get_access_controls {
1.745     raeburn  6735:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6736:     my %access;
                   6737:     my $real_file = $file;
                   6738:     $file =~ s/\.meta$//;
1.745     raeburn  6739:     if (defined($file)) {
1.749     raeburn  6740:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6741:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6742:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6743:             }
                   6744:         }
1.745     raeburn  6745:     } else {
1.749     raeburn  6746:         foreach my $key (keys(%{$current_permissions})) {
                   6747:             if ($key =~ /\0accesscontrol$/) {
                   6748:                 if (defined($group)) {
                   6749:                     if ($key !~ m-^\Q$group\E/-) {
                   6750:                         next;
                   6751:                     }
                   6752:                 }
                   6753:                 my ($fullpath) = split(/\0/,$key);
                   6754:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6755:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6756:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6757:                     }
                   6758:                 }
                   6759:             }
                   6760:         }
                   6761:     }
                   6762:     return %access;
                   6763: }
                   6764: 
                   6765: sub modify_access_controls {
                   6766:     my ($file_name,$changes,$domain,$user)=@_;
                   6767:     my ($outcome,$deloutcome);
                   6768:     my %store_permissions;
                   6769:     my %new_values;
                   6770:     my %new_control;
                   6771:     my %translation;
                   6772:     my @deletions = ();
                   6773:     my $now = time;
                   6774:     if (exists($$changes{'activate'})) {
                   6775:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6776:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6777:             my $numnew = scalar(@newitems);
                   6778:             for (my $i=0; $i<$numnew; $i++) {
                   6779:                 my $newkey = $newitems[$i];
                   6780:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6781:                 if ($newkey =~ /^\d+:/) { 
                   6782:                     $newkey =~ s/^(\d+)/$newid/;
                   6783:                     $translation{$1} = $newid;
                   6784:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6785:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6786:                     $translation{$1} = $newid;
                   6787:                 }
1.749     raeburn  6788:                 $new_values{$file_name."\0".$newkey} = 
                   6789:                                           $$changes{'activate'}{$newitems[$i]};
                   6790:                 $new_control{$newkey} = $now;
                   6791:             }
                   6792:         }
                   6793:     }
                   6794:     my %todelete;
                   6795:     my %changed_items;
                   6796:     foreach my $action ('delete','update') {
                   6797:         if (exists($$changes{$action})) {
                   6798:             if (ref($$changes{$action}) eq 'HASH') {
                   6799:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6800:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6801:                     if ($action eq 'delete') { 
                   6802:                         $todelete{$itemnum} = 1;
                   6803:                     } else {
                   6804:                         $changed_items{$itemnum} = $key;
                   6805:                     }
                   6806:                 }
1.745     raeburn  6807:             }
                   6808:         }
1.749     raeburn  6809:     }
                   6810:     # get lock on access controls for file.
                   6811:     my $lockhash = {
                   6812:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6813:                                                        ':'.$env{'user.domain'},
                   6814:                    }; 
                   6815:     my $tries = 0;
                   6816:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6817:    
                   6818:     while (($gotlock ne 'ok') && $tries <3) {
                   6819:         $tries ++;
                   6820:         sleep 1;
                   6821:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6822:     }
                   6823:     if ($gotlock eq 'ok') {
                   6824:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6825:         my ($tmp)=keys(%curr_permissions);
                   6826:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6827:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6828:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6829:             if (ref($curr_controls) eq 'HASH') {
                   6830:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6831:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6832:                     if (defined($todelete{$itemnum})) {
                   6833:                         push(@deletions,$file_name."\0".$control_item);
                   6834:                     } else {
                   6835:                         if (defined($changed_items{$itemnum})) {
                   6836:                             $new_control{$changed_items{$itemnum}} = $now;
                   6837:                             push(@deletions,$file_name."\0".$control_item);
                   6838:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6839:                         } else {
                   6840:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6841:                         }
                   6842:                     }
1.745     raeburn  6843:                 }
                   6844:             }
                   6845:         }
1.970     raeburn  6846:         my ($group);
                   6847:         if (&is_course($domain,$user)) {
                   6848:             ($group,my $file) = split(/\//,$file_name,2);
                   6849:         }
1.749     raeburn  6850:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6851:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6852:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6853:         #  remove lock
                   6854:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6855:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6856:         my $sqlresult =
1.970     raeburn  6857:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6858:                                     $group);
1.749     raeburn  6859:     } else {
                   6860:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6861:     }
1.749     raeburn  6862:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6863: }
                   6864: 
1.827     raeburn  6865: sub make_public_indefinitely {
                   6866:     my ($requrl) = @_;
                   6867:     my $now = time;
                   6868:     my $action = 'activate';
                   6869:     my $aclnum = 0;
                   6870:     if (&is_portfolio_url($requrl)) {
                   6871:         my (undef,$udom,$unum,$file_name,$group) =
                   6872:             &parse_portfolio_url($requrl);
                   6873:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6874:         my %access_controls = &get_access_controls($current_perms,
                   6875:                                                    $group,$file_name);
                   6876:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6877:             my ($num,$scope,$end,$start) = 
                   6878:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6879:             if ($scope eq 'public') {
                   6880:                 if ($start <= $now && $end == 0) {
                   6881:                     $action = 'none';
                   6882:                 } else {
                   6883:                     $action = 'update';
                   6884:                     $aclnum = $num;
                   6885:                 }
                   6886:                 last;
                   6887:             }
                   6888:         }
                   6889:         if ($action eq 'none') {
                   6890:              return 'ok';
                   6891:         } else {
                   6892:             my %changes;
                   6893:             my $newend = 0;
                   6894:             my $newstart = $now;
                   6895:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6896:             $changes{$action}{$newkey} = {
                   6897:                 type => 'public',
                   6898:                 time => {
                   6899:                     start => $newstart,
                   6900:                     end   => $newend,
                   6901:                 },
                   6902:             };
                   6903:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6904:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6905:             return $outcome;
                   6906:         }
                   6907:     } else {
                   6908:         return 'invalid';
                   6909:     }
                   6910: }
                   6911: 
1.745     raeburn  6912: #------------------------------------------------------Get Marked as Read Only
                   6913: 
                   6914: sub get_marked_as_readonly {
                   6915:     my ($domain,$user,$what,$group) = @_;
                   6916:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6917:     my @readonly_files;
1.629     banghart 6918:     my $cmp1=$what;
                   6919:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6920:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6921:         if (defined($group)) {
                   6922:             if ($file_name !~ m-^\Q$group\E/-) {
                   6923:                 next;
                   6924:             }
                   6925:         }
1.561     banghart 6926:         if (ref($value) eq "ARRAY"){
                   6927:             foreach my $stored_what (@{$value}) {
1.629     banghart 6928:                 my $cmp2=$stored_what;
1.759     albertel 6929:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6930:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6931:                 }
1.629     banghart 6932:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6933:                     push(@readonly_files, $file_name);
1.745     raeburn  6934:                     last;
1.563     banghart 6935:                 } elsif (!defined($what)) {
                   6936:                     push(@readonly_files, $file_name);
1.745     raeburn  6937:                     last;
1.561     banghart 6938:                 }
                   6939:             }
1.745     raeburn  6940:         }
1.561     banghart 6941:     }
                   6942:     return @readonly_files;
                   6943: }
1.577     banghart 6944: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6945: 
1.577     banghart 6946: sub get_marked_as_readonly_hash {
1.745     raeburn  6947:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6948:     my %readonly_files;
1.745     raeburn  6949:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6950:         if (defined($group)) {
                   6951:             if ($file_name !~ m-^\Q$group\E/-) {
                   6952:                 next;
                   6953:             }
                   6954:         }
1.577     banghart 6955:         if (ref($value) eq "ARRAY"){
                   6956:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6957:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6958:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6959:                         if ($lock_descriptor eq 'graded') {
                   6960:                             $readonly_files{$file_name} = 'graded';
                   6961:                         } elsif ($lock_descriptor eq 'handback') {
                   6962:                             $readonly_files{$file_name} = 'handback';
                   6963:                         } else {
                   6964:                             if (!exists($readonly_files{$file_name})) {
                   6965:                                 $readonly_files{$file_name} = 'locked';
                   6966:                             }
                   6967:                         }
1.745     raeburn  6968:                     }
1.750     banghart 6969:                 } 
1.577     banghart 6970:             }
                   6971:         } 
                   6972:     }
                   6973:     return %readonly_files;
                   6974: }
1.559     banghart 6975: # ------------------------------------------------------------ Unmark as Read Only
                   6976: 
                   6977: sub unmark_as_readonly {
1.629     banghart 6978:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6979:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6980:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6981:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6982:     my $symb_crs = $what;
                   6983:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6984:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6985:     my ($tmp)=keys(%current_permissions);
                   6986:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6987:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6988:     foreach my $file (@readonly_files) {
1.759     albertel 6989: 	my $clean_file = &declutter_portfile($file);
                   6990: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6991: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6992:         my @new_locks;
                   6993:         my @del_keys;
                   6994:         if (ref($current_locks) eq "ARRAY"){
                   6995:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6996:                 my $compare=$locker;
1.749     raeburn  6997:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6998:                     $compare=join('',@{$locker});
1.746     raeburn  6999:                     if ($compare ne $symb_crs) {
                   7000:                         push(@new_locks, $locker);
                   7001:                     }
1.563     banghart 7002:                 }
                   7003:             }
1.650     albertel 7004:             if (scalar(@new_locks) > 0) {
1.563     banghart 7005:                 $current_permissions{$file} = \@new_locks;
                   7006:             } else {
                   7007:                 push(@del_keys, $file);
1.613     albertel 7008:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7009:                 delete($current_permissions{$file});
1.563     banghart 7010:             }
                   7011:         }
1.561     banghart 7012:     }
1.613     albertel 7013:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7014:     return;
                   7015: }
1.512     banghart 7016: 
1.17      www      7017: # ------------------------------------------------------------ Directory lister
                   7018: 
                   7019: sub dirlist {
1.955     raeburn  7020:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7021:     $uri=~s/^\///;
                   7022:     $uri=~s/\/$//;
1.253     stredwic 7023:     my ($udom, $uname);
1.955     raeburn  7024:     if ($getuserdir) {
1.253     stredwic 7025:         $udom = $userdomain;
                   7026:         $uname = $username;
1.955     raeburn  7027:     } else {
                   7028:         (undef,$udom,$uname)=split(/\//,$uri);
                   7029:         if(defined($userdomain)) {
                   7030:             $udom = $userdomain;
                   7031:         }
                   7032:         if(defined($username)) {
                   7033:             $uname = $username;
                   7034:         }
1.253     stredwic 7035:     }
1.955     raeburn  7036:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7037: 
1.955     raeburn  7038:     $dirRoot = $perlvar{'lonDocRoot'};
                   7039:     if (defined($getpropath)) {
                   7040:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7041:         $dirRoot =~ s/\/$//;
1.955     raeburn  7042:     } elsif (defined($getuserdir)) {
                   7043:         my $subdir=$uname.'__';
                   7044:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7045:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7046:                    ."/$udom/$subdir/$uname";
                   7047:     } elsif (defined($alternateRoot)) {
                   7048:         $dirRoot = $alternateRoot;
1.751     banghart 7049:     }
1.253     stredwic 7050: 
                   7051:     if($udom) {
                   7052:         if($uname) {
1.955     raeburn  7053:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7054:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7055:                               .':'.&escape($uname).':'.&escape($udom),
                   7056:                               &homeserver($uname,$udom));
                   7057:             if ($listing eq 'unknown_cmd') {
                   7058:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7059:                                   &homeserver($uname,$udom));
                   7060:             } else {
                   7061:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7062:             }
1.605     matthew  7063:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7064:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7065: 				  &homeserver($uname,$udom));
1.605     matthew  7066:                 @listing_results = split(/:/,$listing);
                   7067:             } else {
                   7068:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7069:             }
                   7070:             return @listing_results;
1.955     raeburn  7071:         } elsif(!$alternateRoot) {
1.800     albertel 7072:             my %allusers;
1.841     albertel 7073: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7074:  	    foreach my $tryserver (keys(%servers)) {
                   7075:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7076:                                   &escape($udom),$tryserver);
                   7077:                 if ($listing eq 'unknown_cmd') {
                   7078: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7079: 				      $udom, $tryserver);
                   7080:                 } else {
                   7081:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7082:                 }
1.841     albertel 7083: 		if ($listing eq 'unknown_cmd') {
                   7084: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7085: 				      $udom, $tryserver);
                   7086: 		    @listing_results = split(/:/,$listing);
                   7087: 		} else {
                   7088: 		    @listing_results =
                   7089: 			map { &unescape($_); } split(/:/,$listing);
                   7090: 		}
                   7091: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7092: 		    $listing_results[0] ne 'empty'       &&
                   7093: 		    $listing_results[0] ne 'con_lost') {
                   7094: 		    foreach my $line (@listing_results) {
                   7095: 			my ($entry) = split(/&/,$line,2);
                   7096: 			$allusers{$entry} = 1;
                   7097: 		    }
                   7098: 		}
1.253     stredwic 7099:             }
                   7100:             my $alluserstr='';
1.800     albertel 7101:             foreach my $user (sort(keys(%allusers))) {
                   7102:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7103:             }
                   7104:             $alluserstr=~s/:$//;
                   7105:             return split(/:/,$alluserstr);
                   7106:         } else {
1.800     albertel 7107:             return ('missing user name');
1.253     stredwic 7108:         }
1.955     raeburn  7109:     } elsif(!defined($getpropath)) {
1.841     albertel 7110:         my @all_domains = sort(&all_domains());
1.955     raeburn  7111:         foreach my $domain (@all_domains) {
                   7112:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7113:         }
                   7114:         return @all_domains;
                   7115:     } else {
1.800     albertel 7116:         return ('missing domain');
1.275     stredwic 7117:     }
                   7118: }
                   7119: 
                   7120: # --------------------------------------------- GetFileTimestamp
                   7121: # This function utilizes dirlist and returns the date stamp for
                   7122: # when it was last modified.  It will also return an error of -1
                   7123: # if an error occurs
                   7124: 
                   7125: sub GetFileTimestamp {
1.955     raeburn  7126:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7127:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7128:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7129:     my ($fileStat) = 
                   7130:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7131:                                  undef,$getuserdir);
1.275     stredwic 7132:     my @stats = split('&', $fileStat);
                   7133:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7134:         # @stats contains first the filename, then the stat output
                   7135:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7136:     } else {
                   7137:         return -1;
1.253     stredwic 7138:     }
1.26      www      7139: }
                   7140: 
1.712     albertel 7141: sub stat_file {
                   7142:     my ($uri) = @_;
1.787     albertel 7143:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7144: 
1.955     raeburn  7145:     my ($udom,$uname,$file);
1.712     albertel 7146:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7147: 	($udom,$uname,$file) =
1.811     albertel 7148: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7149: 	$file = 'userfiles/'.$file;
                   7150:     }
                   7151:     if ($uri =~ m-^/res/-) {
                   7152: 	($udom,$uname) = 
1.807     albertel 7153: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7154: 	$file = $uri;
                   7155:     }
                   7156: 
                   7157:     if (!$udom || !$uname || !$file) {
                   7158: 	# unable to handle the uri
                   7159: 	return ();
                   7160:     }
1.956     raeburn  7161:     my $getpropath;
                   7162:     if ($file =~ /^userfiles\//) {
                   7163:         $getpropath = 1;
                   7164:     }
1.955     raeburn  7165:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7166:     my @stats = split('&', $result);
1.721     banghart 7167:     
1.712     albertel 7168:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7169: 	shift(@stats); #filename is first
                   7170: 	return @stats;
                   7171:     }
                   7172:     return ();
                   7173: }
                   7174: 
1.26      www      7175: # -------------------------------------------------------- Value of a Condition
                   7176: 
1.713     albertel 7177: # gets the value of a specific preevaluated condition
                   7178: #    stored in the string  $env{user.state.<cid>}
                   7179: # or looks up a condition reference in the bighash and if if hasn't
                   7180: # already been evaluated recurses into docondval to get the value of
                   7181: # the condition, then memoizing it to 
                   7182: #   $env{user.state.<cid>.<condition>}
1.40      www      7183: sub directcondval {
                   7184:     my $number=shift;
1.620     albertel 7185:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7186: 	&Apache::lonuserstate::evalstate();
                   7187:     }
1.713     albertel 7188:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7189: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7190:     } elsif ($number =~ /^_/) {
                   7191: 	my $sub_condition;
                   7192: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7193: 		&GDBM_READER(),0640)) {
                   7194: 	    $sub_condition=$bighash{'conditions'.$number};
                   7195: 	    untie(%bighash);
                   7196: 	}
                   7197: 	my $value = &docondval($sub_condition);
1.949     raeburn  7198: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7199: 	return $value;
                   7200:     }
1.620     albertel 7201:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7202:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7203:     } else {
                   7204:        return 2;
                   7205:     }
                   7206: }
                   7207: 
1.713     albertel 7208: # get the collection of conditions for this resource
1.26      www      7209: sub condval {
                   7210:     my $condidx=shift;
1.54      www      7211:     my $allpathcond='';
1.713     albertel 7212:     foreach my $cond (split(/\|/,$condidx)) {
                   7213: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7214: 	    $allpathcond.=
                   7215: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7216: 	}
1.191     harris41 7217:     }
1.54      www      7218:     $allpathcond=~s/\|$//;
1.713     albertel 7219:     return &docondval($allpathcond);
                   7220: }
                   7221: 
                   7222: #evaluates an expression of conditions
                   7223: sub docondval {
                   7224:     my ($allpathcond) = @_;
                   7225:     my $result=0;
                   7226:     if ($env{'request.course.id'}
                   7227: 	&& defined($allpathcond)) {
                   7228: 	my $operand='|';
                   7229: 	my @stack;
                   7230: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7231: 	    if ($chunk eq '(') {
                   7232: 		push @stack,($operand,$result);
                   7233: 	    } elsif ($chunk eq ')') {
                   7234: 		my $before=pop @stack;
                   7235: 		if (pop @stack eq '&') {
                   7236: 		    $result=$result>$before?$before:$result;
                   7237: 		} else {
                   7238: 		    $result=$result>$before?$result:$before;
                   7239: 		}
                   7240: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7241: 		$operand=$chunk;
                   7242: 	    } else {
                   7243: 		my $new=directcondval($chunk);
                   7244: 		if ($operand eq '&') {
                   7245: 		    $result=$result>$new?$new:$result;
                   7246: 		} else {
                   7247: 		    $result=$result>$new?$result:$new;
                   7248: 		}
                   7249: 	    }
                   7250: 	}
1.26      www      7251:     }
                   7252:     return $result;
1.421     albertel 7253: }
                   7254: 
                   7255: # ---------------------------------------------------- Devalidate courseresdata
                   7256: 
                   7257: sub devalidatecourseresdata {
                   7258:     my ($coursenum,$coursedomain)=@_;
                   7259:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7260:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7261: }
                   7262: 
1.763     www      7263: 
1.200     www      7264: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7265: #
                   7266: #  Parameters:
                   7267: #      $coursenum    - Number of the course.
                   7268: #      $coursedomain - Domain at which the course was created.
                   7269: #  Returns:
                   7270: #     A hash of the course parameters along (I think) with timestamps
                   7271: #     and version info.
1.877     foxr     7272: 
1.624     albertel 7273: sub get_courseresdata {
                   7274:     my ($coursenum,$coursedomain)=@_;
1.200     www      7275:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7276:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7277:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7278:     my %dumpreply;
1.417     albertel 7279:     unless (defined($cached)) {
1.624     albertel 7280: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7281: 	$result=\%dumpreply;
1.251     albertel 7282: 	my ($tmp) = keys(%dumpreply);
                   7283: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7284: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7285: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7286: 	    return $tmp;
1.416     albertel 7287: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7288: 	    $result=undef;
1.599     albertel 7289: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7290: 	}
                   7291:     }
1.624     albertel 7292:     return $result;
                   7293: }
                   7294: 
1.633     albertel 7295: sub devalidateuserresdata {
                   7296:     my ($uname,$udom)=@_;
                   7297:     my $hashid="$udom:$uname";
                   7298:     &devalidate_cache_new('userres',$hashid);
                   7299: }
                   7300: 
1.624     albertel 7301: sub get_userresdata {
                   7302:     my ($uname,$udom)=@_;
                   7303:     #most student don\'t have any data set, check if there is some data
                   7304:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7305: 
                   7306:     my $hashid="$udom:$uname";
                   7307:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7308:     if (!defined($cached)) {
                   7309: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7310: 	$result=\%resourcedata;
                   7311: 	&do_cache_new('userres',$hashid,$result,600);
                   7312:     }
                   7313:     my ($tmp)=keys(%$result);
                   7314:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7315: 	return $result;
                   7316:     }
                   7317:     #error 2 occurs when the .db doesn't exist
                   7318:     if ($tmp!~/error: 2 /) {
1.672     albertel 7319: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7320: 		 " Trying to get resource data for ".
                   7321: 		 $uname." at ".$udom.": ".
                   7322: 		 $tmp."</font>");
                   7323:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7324: 	#&EXT_cache_set($udom,$uname);
                   7325: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7326: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7327:     }
                   7328:     return $tmp;
                   7329: }
1.879     foxr     7330: #----------------------------------------------- resdata - return resource data
                   7331: #  Purpose:
                   7332: #    Return resource data for either users or for a course.
                   7333: #  Parameters:
                   7334: #     $name      - Course/user name.
                   7335: #     $domain    - Name of the domain the user/course is registered on.
                   7336: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7337: #     @which     - Array of names of resources desired.
                   7338: #  Returns:
                   7339: #     The value of the first reasource in @which that is found in the
                   7340: #     resource hash.
                   7341: #  Exceptional Conditions:
                   7342: #     If the $type passed in is not valid (not the string 'course' or 
                   7343: #     'user', an undefined  reference is returned.
                   7344: #     If none of the resources are found, an undef is returned
1.624     albertel 7345: sub resdata {
                   7346:     my ($name,$domain,$type,@which)=@_;
                   7347:     my $result;
                   7348:     if ($type eq 'course') {
                   7349: 	$result=&get_courseresdata($name,$domain);
                   7350:     } elsif ($type eq 'user') {
                   7351: 	$result=&get_userresdata($name,$domain);
                   7352:     }
                   7353:     if (!ref($result)) { return $result; }    
1.251     albertel 7354:     foreach my $item (@which) {
1.927     albertel 7355: 	if (defined($result->{$item->[0]})) {
                   7356: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7357: 	}
1.250     albertel 7358:     }
1.291     albertel 7359:     return undef;
1.200     www      7360: }
                   7361: 
1.379     matthew  7362: #
                   7363: # EXT resource caching routines
                   7364: #
                   7365: 
                   7366: sub clear_EXT_cache_status {
1.383     albertel 7367:     &delenv('cache.EXT.');
1.379     matthew  7368: }
                   7369: 
                   7370: sub EXT_cache_status {
                   7371:     my ($target_domain,$target_user) = @_;
1.383     albertel 7372:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7373:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7374:         # We know already the user has no data
                   7375:         return 1;
                   7376:     } else {
                   7377:         return 0;
                   7378:     }
                   7379: }
                   7380: 
                   7381: sub EXT_cache_set {
                   7382:     my ($target_domain,$target_user) = @_;
1.383     albertel 7383:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7384:     #&appenv({$cachename => time});
1.379     matthew  7385: }
                   7386: 
1.28      www      7387: # --------------------------------------------------------- Value of a Variable
1.58      www      7388: sub EXT {
1.715     albertel 7389: 
1.395     albertel 7390:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7391:     unless ($varname) { return ''; }
1.218     albertel 7392:     #get real user name/domain, courseid and symb
                   7393:     my $courseid;
1.359     albertel 7394:     my $publicuser;
1.427     www      7395:     if ($symbparm) {
                   7396: 	$symbparm=&get_symb_from_alias($symbparm);
                   7397:     }
1.218     albertel 7398:     if (!($uname && $udom)) {
1.790     albertel 7399:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7400:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7401:     } else {
1.620     albertel 7402: 	$courseid=$env{'request.course.id'};
1.218     albertel 7403:     }
1.48      www      7404:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7405:     my $rest;
1.320     albertel 7406:     if (defined($therest[0])) {
1.48      www      7407:        $rest=join('.',@therest);
                   7408:     } else {
                   7409:        $rest='';
                   7410:     }
1.320     albertel 7411: 
1.57      www      7412:     my $qualifierrest=$qualifier;
                   7413:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7414:     my $spacequalifierrest=$space;
                   7415:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7416:     if ($realm eq 'user') {
1.48      www      7417: # --------------------------------------------------------------- user.resource
                   7418: 	if ($space eq 'resource') {
1.651     albertel 7419: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7420: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7421: 		 &&
1.744     albertel 7422: 		 ($symbparm eq &symbread()) ) {	
                   7423: 		# if we are in the middle of processing the resource the
                   7424: 		# get the value we are planning on committing
                   7425:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7426:                     return $Apache::lonhomework::results{$qualifierrest};
                   7427:                 } else {
                   7428:                     return $Apache::lonhomework::history{$qualifierrest};
                   7429:                 }
1.335     albertel 7430: 	    } else {
1.359     albertel 7431: 		my %restored;
1.620     albertel 7432: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7433: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7434: 		} else {
                   7435: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7436: 		}
1.335     albertel 7437: 		return $restored{$qualifierrest};
                   7438: 	    }
1.48      www      7439: # ----------------------------------------------------------------- user.access
                   7440:         } elsif ($space eq 'access') {
1.218     albertel 7441: 	    # FIXME - not supporting calls for a specific user
1.48      www      7442:             return &allowed($qualifier,$rest);
                   7443: # ------------------------------------------ user.preferences, user.environment
                   7444:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7445: 	    if (($uname eq $env{'user.name'}) &&
                   7446: 		($udom eq $env{'user.domain'})) {
                   7447: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7448: 	    } else {
1.359     albertel 7449: 		my %returnhash;
                   7450: 		if (!$publicuser) {
                   7451: 		    %returnhash=&userenvironment($udom,$uname,
                   7452: 						 $qualifierrest);
                   7453: 		}
1.218     albertel 7454: 		return $returnhash{$qualifierrest};
                   7455: 	    }
1.48      www      7456: # ----------------------------------------------------------------- user.course
                   7457:         } elsif ($space eq 'course') {
1.218     albertel 7458: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7459:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7460: # ------------------------------------------------------------------- user.role
                   7461:         } elsif ($space eq 'role') {
1.218     albertel 7462: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7463:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7464:             if ($qualifier eq 'value') {
                   7465: 		return $role;
                   7466:             } elsif ($qualifier eq 'extent') {
                   7467:                 return $where;
                   7468:             }
                   7469: # ----------------------------------------------------------------- user.domain
                   7470:         } elsif ($space eq 'domain') {
1.218     albertel 7471:             return $udom;
1.48      www      7472: # ------------------------------------------------------------------- user.name
                   7473:         } elsif ($space eq 'name') {
1.218     albertel 7474:             return $uname;
1.48      www      7475: # ---------------------------------------------------- Any other user namespace
1.29      www      7476:         } else {
1.359     albertel 7477: 	    my %reply;
                   7478: 	    if (!$publicuser) {
                   7479: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7480: 	    }
                   7481: 	    return $reply{$qualifierrest};
1.48      www      7482:         }
1.236     www      7483:     } elsif ($realm eq 'query') {
                   7484: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7485:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7486: 						[$spacequalifierrest]);
1.620     albertel 7487: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7488:    } elsif ($realm eq 'request') {
1.48      www      7489: # ------------------------------------------------------------- request.browser
                   7490:         if ($space eq 'browser') {
1.430     www      7491: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7492: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7493: 		    return 1;
                   7494: 		} else {
                   7495: 		    return 0;
                   7496: 		}
                   7497: 	    } else {
1.620     albertel 7498: 		return $env{'browser.'.$qualifier};
1.430     www      7499: 	    }
1.57      www      7500: # ------------------------------------------------------------ request.filename
                   7501:         } else {
1.620     albertel 7502:             return $env{'request.'.$spacequalifierrest};
1.29      www      7503:         }
1.28      www      7504:     } elsif ($realm eq 'course') {
1.48      www      7505: # ---------------------------------------------------------- course.description
1.620     albertel 7506:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7507:     } elsif ($realm eq 'resource') {
1.165     www      7508: 
1.620     albertel 7509: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7510: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7511: 	}
1.693     albertel 7512: 
                   7513: 	if ($space eq 'title') {
                   7514: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7515: 	    return &gettitle($symbparm);
                   7516: 	}
                   7517: 	
                   7518: 	if ($space eq 'map') {
                   7519: 	    my ($map) = &decode_symb($symbparm);
                   7520: 	    return &symbread($map);
                   7521: 	}
1.905     albertel 7522: 	if ($space eq 'filename') {
                   7523: 	    if ($symbparm) {
                   7524: 		return &clutter((&decode_symb($symbparm))[2]);
                   7525: 	    }
                   7526: 	    return &hreflocation('',$env{'request.filename'});
                   7527: 	}
1.693     albertel 7528: 
                   7529: 	my ($section, $group, @groups);
1.593     albertel 7530: 	my ($courselevelm,$courselevel);
1.539     albertel 7531: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7532: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7533: 
1.218     albertel 7534: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7535: 
1.60      www      7536: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7537: 	    my $symbp=$symbparm;
1.735     albertel 7538: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7539: 
                   7540: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7541: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7542: 
1.620     albertel 7543: 	    if (($env{'user.name'} eq $uname) &&
                   7544: 		($env{'user.domain'} eq $udom)) {
                   7545: 		$section=$env{'request.course.sec'};
1.733     raeburn  7546:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7547:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7548: 	    } else {
1.539     albertel 7549: 		if (! defined($usection)) {
1.551     albertel 7550: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7551: 		} else {
                   7552: 		    $section = $usection;
                   7553: 		}
1.733     raeburn  7554:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7555: 	    }
                   7556: 
                   7557: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7558: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7559: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7560: 
1.593     albertel 7561: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7562: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7563: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7564: 
1.60      www      7565: # ----------------------------------------------------------- first, check user
1.624     albertel 7566: 
                   7567: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7568: 				       ([$courselevelr,'resource'],
                   7569: 					[$courselevelm,'map'     ],
                   7570: 					[$courselevel, 'course'  ]));
1.931     albertel 7571: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7572: 
1.594     albertel 7573: # ------------------------------------------------ second, check some of course
1.684     raeburn  7574:             my $coursereply;
1.691     raeburn  7575:             if (@groups > 0) {
                   7576:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7577:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7578:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7579:             }
1.96      www      7580: 
1.684     raeburn  7581: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7582: 				  $env{'course.'.$courseid.'.domain'},
                   7583: 				  'course',
                   7584: 				  ([$seclevelr,   'resource'],
                   7585: 				   [$seclevelm,   'map'     ],
                   7586: 				   [$seclevel,    'course'  ],
                   7587: 				   [$courselevelr,'resource']));
                   7588: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7589: 
1.60      www      7590: # ------------------------------------------------------ third, check map parms
1.218     albertel 7591: 	    my %parmhash=();
                   7592: 	    my $thisparm='';
                   7593: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7594: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7595: 		    &GDBM_READER(),0640)) {
1.218     albertel 7596: 		$thisparm=$parmhash{$symbparm};
                   7597: 		untie(%parmhash);
                   7598: 	    }
1.927     albertel 7599: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7600: 	}
1.594     albertel 7601: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7602: 
1.218     albertel 7603: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7604: 	my $filename;
                   7605: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7606: 	if ($symbparm) {
1.409     www      7607: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7608: 	} else {
1.620     albertel 7609: 	    $filename=$env{'request.filename'};
1.282     albertel 7610: 	}
                   7611: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7612: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7613: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7614: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7615: 
1.927     albertel 7616: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7617: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7618: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7619: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7620: 				     $env{'course.'.$courseid.'.domain'},
                   7621: 				     'course',
1.927     albertel 7622: 				     ([$courselevelm,'map'   ],
                   7623: 				      [$courselevel, 'course']));
                   7624: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7625: 	}
1.145     www      7626: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7627: 	unless ($space eq '0') {
1.336     albertel 7628: 	    my @parts=split(/_/,$space);
                   7629: 	    my $id=pop(@parts);
                   7630: 	    my $part=join('_',@parts);
                   7631: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7632: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7633: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7634: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7635: 	}
1.395     albertel 7636: 	if ($recurse) { return undef; }
                   7637: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7638: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7639: # ---------------------------------------------------- Any other user namespace
                   7640:     } elsif ($realm eq 'environment') {
                   7641: # ----------------------------------------------------------------- environment
1.620     albertel 7642: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7643: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7644: 	} else {
1.770     albertel 7645: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7646: 		return '';
                   7647: 	    }
1.219     albertel 7648: 	    my %returnhash=&userenvironment($udom,$uname,
                   7649: 					    $spacequalifierrest);
                   7650: 	    return $returnhash{$spacequalifierrest};
                   7651: 	}
1.28      www      7652:     } elsif ($realm eq 'system') {
1.48      www      7653: # ----------------------------------------------------------------- system.time
                   7654: 	if ($space eq 'time') {
                   7655: 	    return time;
                   7656:         }
1.696     albertel 7657:     } elsif ($realm eq 'server') {
                   7658: # ----------------------------------------------------------------- system.time
                   7659: 	if ($space eq 'name') {
                   7660: 	    return $ENV{'SERVER_NAME'};
                   7661:         }
1.28      www      7662:     }
1.48      www      7663:     return '';
1.61      www      7664: }
                   7665: 
1.927     albertel 7666: sub get_reply {
                   7667:     my ($reply_value) = @_;
1.940     raeburn  7668:     if (ref($reply_value) eq 'ARRAY') {
                   7669:         if (wantarray) {
                   7670: 	    return @$reply_value;
                   7671:         }
                   7672:         return $reply_value->[0];
                   7673:     } else {
                   7674:         return $reply_value;
1.927     albertel 7675:     }
                   7676: }
                   7677: 
1.691     raeburn  7678: sub check_group_parms {
                   7679:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7680:     my @groupitems = ();
                   7681:     my $resultitem;
1.927     albertel 7682:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7683:     foreach my $group (@{$groups}) {
                   7684:         foreach my $level (@levels) {
1.927     albertel 7685:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7686:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7687:         }
                   7688:     }
                   7689:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7690:                             $env{'course.'.$courseid.'.domain'},
                   7691:                                      'course',@groupitems);
                   7692:     return $coursereply;
                   7693: }
                   7694: 
                   7695: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7696:     my ($courseid,@groups) = @_;
                   7697:     @groups = sort(@groups);
1.691     raeburn  7698:     return @groups;
                   7699: }
                   7700: 
1.395     albertel 7701: sub packages_tab_default {
                   7702:     my ($uri,$varname)=@_;
                   7703:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7704: 
                   7705:     my (@extension,@specifics,$do_default);
                   7706:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7707: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7708: 	if ($pack_type eq 'default') {
                   7709: 	    $do_default=1;
                   7710: 	} elsif ($pack_type eq 'extension') {
                   7711: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7712: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7713: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7714: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7715: 	}
                   7716:     }
                   7717:     # first look for a package that matches the requested part id
                   7718:     foreach my $package (@specifics) {
                   7719: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7720: 	next if ($pack_part ne $part);
                   7721: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7722: 	    return $packagetab{"$pack_type&$name&default"};
                   7723: 	}
                   7724:     }
                   7725:     # look for any possible matching non extension_ package
                   7726:     foreach my $package (@specifics) {
                   7727: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7728: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7729: 	    return $packagetab{"$pack_type&$name&default"};
                   7730: 	}
1.585     albertel 7731: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7732: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7733: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7734: 	}
                   7735:     }
1.738     albertel 7736:     # look for any posible extension_ match
                   7737:     foreach my $package (@extension) {
                   7738: 	my ($package,$pack_type)=@{$package};
                   7739: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7740: 	    return $packagetab{"$pack_type&$name&default"};
                   7741: 	}
                   7742: 	if (defined($packagetab{$package."&$name&default"})) {
                   7743: 	    return $packagetab{$package."&$name&default"};
                   7744: 	}
                   7745:     }
                   7746:     # look for a global default setting
                   7747:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7748: 	return $packagetab{"default&$name&default"};
                   7749:     }
1.395     albertel 7750:     return undef;
                   7751: }
                   7752: 
1.334     albertel 7753: sub add_prefix_and_part {
                   7754:     my ($prefix,$part)=@_;
                   7755:     my $keyroot;
                   7756:     if (defined($prefix) && $prefix !~ /^__/) {
                   7757: 	# prefix that has a part already
                   7758: 	$keyroot=$prefix;
                   7759:     } elsif (defined($prefix)) {
                   7760: 	# prefix that is missing a part
                   7761: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7762:     } else {
                   7763: 	# no prefix at all
                   7764: 	if (defined($part)) { $keyroot='_'.$part; }
                   7765:     }
                   7766:     return $keyroot;
                   7767: }
                   7768: 
1.71      www      7769: # ---------------------------------------------------------------- Get metadata
                   7770: 
1.599     albertel 7771: my %metaentry;
1.71      www      7772: sub metadata {
1.176     www      7773:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7774:     $uri=&declutter($uri);
1.288     albertel 7775:     # if it is a non metadata possible uri return quickly
1.529     albertel 7776:     if (($uri eq '') || 
                   7777: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7778: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7779:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7780: 	return undef;
                   7781:     }
                   7782:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7783: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7784: 	return undef;
1.288     albertel 7785:     }
1.73      www      7786:     my $filename=$uri;
                   7787:     $uri=~s/\.meta$//;
1.172     www      7788: #
                   7789: # Is the metadata already cached?
1.177     www      7790: # Look at timestamp of caching
1.172     www      7791: # Everything is cached by the main uri, libraries are never directly cached
                   7792: #
1.428     albertel 7793:     if (!defined($liburi)) {
1.599     albertel 7794: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7795: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7796:     }
                   7797:     {
1.172     www      7798: #
                   7799: # Is this a recursive call for a library?
                   7800: #
1.599     albertel 7801: #	if (! exists($metacache{$uri})) {
                   7802: #	    $metacache{$uri}={};
                   7803: #	}
1.924     albertel 7804: 	my $cachetime = 60*60;
1.171     www      7805:         if ($liburi) {
                   7806: 	    $liburi=&declutter($liburi);
                   7807:             $filename=$liburi;
1.401     bowersj2 7808:         } else {
1.599     albertel 7809: 	    &devalidate_cache_new('meta',$uri);
                   7810: 	    undef(%metaentry);
1.401     bowersj2 7811: 	}
1.140     www      7812:         my %metathesekeys=();
1.73      www      7813:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7814: 	my $metastring;
1.924     albertel 7815: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7816: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7817: 	    $metastring = 
1.929     albertel 7818: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7819: 					  ('grade_target' => 'meta'));
                   7820: 	    $cachetime = 1; # only want this cached in the child not long term
                   7821: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7822: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7823: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7824: 	    $metastring=&getfile($file);
1.489     albertel 7825: 	}
1.208     albertel 7826:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7827:         my $token;
1.140     www      7828:         undef %metathesekeys;
1.71      www      7829:         while ($token=$parser->get_token) {
1.339     albertel 7830: 	    if ($token->[0] eq 'S') {
                   7831: 		if (defined($token->[2]->{'package'})) {
1.172     www      7832: #
                   7833: # This is a package - get package info
                   7834: #
1.339     albertel 7835: 		    my $package=$token->[2]->{'package'};
                   7836: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7837: 		    if (defined($token->[2]->{'id'})) { 
                   7838: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7839: 		    }
1.599     albertel 7840: 		    if ($metaentry{':packages'}) {
                   7841: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7842: 		    } else {
1.599     albertel 7843: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7844: 		    }
1.736     albertel 7845: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7846: 			my $part=$keyroot;
                   7847: 			$part=~s/^\_//;
1.736     albertel 7848: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7849: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7850: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7851: 			    # ignore package.tab specified default values
                   7852:                             # here &package_tab_default() will fetch those
                   7853: 			    if ($subp eq 'default') { next; }
1.736     albertel 7854: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7855: 			    my $unikey;
                   7856: 			    if ($pack =~ /_0$/) {
                   7857: 				$unikey='parameter_0_'.$name;
                   7858: 				$part=0;
                   7859: 			    } else {
                   7860: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7861: 			    }
1.339     albertel 7862: 			    if ($subp eq 'display') {
                   7863: 				$value.=' [Part: '.$part.']';
                   7864: 			    }
1.599     albertel 7865: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7866: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7867: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7868: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7869: 			    }
1.599     albertel 7870: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7871: 				$metaentry{':'.$unikey}=
                   7872: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7873: 			    }
1.339     albertel 7874: 			}
                   7875: 		    }
                   7876: 		} else {
1.172     www      7877: #
                   7878: # This is not a package - some other kind of start tag
1.339     albertel 7879: #
                   7880: 		    my $entry=$token->[1];
                   7881: 		    my $unikey;
                   7882: 		    if ($entry eq 'import') {
                   7883: 			$unikey='';
                   7884: 		    } else {
                   7885: 			$unikey=$entry;
                   7886: 		    }
                   7887: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7888: 
                   7889: 		    if (defined($token->[2]->{'id'})) { 
                   7890: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7891: 		    }
1.175     www      7892: 
1.339     albertel 7893: 		    if ($entry eq 'import') {
1.175     www      7894: #
                   7895: # Importing a library here
1.339     albertel 7896: #
                   7897: 			if ($depthcount<20) {
                   7898: 			    my $location=$parser->get_text('/import');
                   7899: 			    my $dir=$filename;
                   7900: 			    $dir=~s|[^/]*$||;
                   7901: 			    $location=&filelocation($dir,$location);
1.736     albertel 7902: 			    my $metadata = 
                   7903: 				&metadata($uri,'keys', $location,$unikey,
                   7904: 					  $depthcount+1);
                   7905: 			    foreach my $meta (split(',',$metadata)) {
                   7906: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7907: 				$metathesekeys{$meta}=1;
1.339     albertel 7908: 			    }
                   7909: 			}
                   7910: 		    } else { 
                   7911: 			
                   7912: 			if (defined($token->[2]->{'name'})) { 
                   7913: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7914: 			}
                   7915: 			$metathesekeys{$unikey}=1;
1.736     albertel 7916: 			foreach my $param (@{$token->[3]}) {
                   7917: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7918: 				$token->[2]->{$param};
1.339     albertel 7919: 			}
                   7920: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7921: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7922: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7923: 		 # only ws inside the tag, and not in default, so use default
                   7924: 		 # as value
1.599     albertel 7925: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7926: 			} elsif ( $internaltext =~ /\S/ ) {
                   7927: 		  # something interesting inside the tag
                   7928: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7929: 			} else {
1.908     albertel 7930: 		  # no interesting values, don't set a default
1.339     albertel 7931: 			}
1.172     www      7932: # end of not-a-package not-a-library import
1.339     albertel 7933: 		    }
1.172     www      7934: # end of not-a-package start tag
1.339     albertel 7935: 		}
1.172     www      7936: # the next is the end of "start tag"
1.339     albertel 7937: 	    }
                   7938: 	}
1.483     albertel 7939: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7940: 	$extension = lc($extension);
                   7941: 	if ($extension eq 'htm') { $extension='html'; }
                   7942: 
1.737     albertel 7943: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7944: 	    #no specific packages #how's our extension
                   7945: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7946: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7947: 					 \%metathesekeys);
                   7948: 	}
1.883     albertel 7949: 
                   7950: 	if (!exists($metaentry{':packages'})
                   7951: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7952: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7953: 		#no specific packages well let's get default then
                   7954: 		if ($key!~/^default&/) { next; }
1.488     albertel 7955: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7956: 					     \%metathesekeys);
                   7957: 	    }
                   7958: 	}
1.338     www      7959: # are there custom rights to evaluate
1.599     albertel 7960: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7961: 
1.338     www      7962:     #
                   7963:     # Importing a rights file here
1.339     albertel 7964:     #
                   7965: 	    unless ($depthcount) {
1.599     albertel 7966: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7967: 		my $dir=$filename;
                   7968: 		$dir=~s|[^/]*$||;
                   7969: 		$location=&filelocation($dir,$location);
1.736     albertel 7970: 		my $rights_metadata =
                   7971: 		    &metadata($uri,'keys',$location,'_rights',
                   7972: 			      $depthcount+1);
                   7973: 		foreach my $rights (split(',',$rights_metadata)) {
                   7974: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7975: 		    $metathesekeys{$rights}=1;
1.339     albertel 7976: 		}
                   7977: 	    }
                   7978: 	}
1.737     albertel 7979: 	# uniqifiy package listing
                   7980: 	my %seen;
                   7981: 	my @uniq_packages =
                   7982: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7983: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7984: 
                   7985: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7986: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7987: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7988: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7989: # this is the end of "was not already recently cached
1.71      www      7990:     }
1.599     albertel 7991:     return $metaentry{':'.$what};
1.261     albertel 7992: }
                   7993: 
1.488     albertel 7994: sub metadata_create_package_def {
1.483     albertel 7995:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7996:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7997:     if ($subp eq 'default') { next; }
                   7998:     
1.599     albertel 7999:     if (defined($metaentry{':packages'})) {
                   8000: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8001:     } else {
1.599     albertel 8002: 	$metaentry{':packages'}=$package;
1.483     albertel 8003:     }
                   8004:     my $value=$packagetab{$key};
                   8005:     my $unikey;
                   8006:     $unikey='parameter_0_'.$name;
1.599     albertel 8007:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8008:     $$metathesekeys{$unikey}=1;
1.599     albertel 8009:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8010: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8011:     }
1.599     albertel 8012:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8013: 	$metaentry{':'.$unikey}=
                   8014: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8015:     }
                   8016: }
                   8017: 
1.261     albertel 8018: sub metadata_generate_part0 {
                   8019:     my ($metadata,$metacache,$uri) = @_;
                   8020:     my %allnames;
1.737     albertel 8021:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8022: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8023: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8024: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8025: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8026: 	    $allnames{$name}=$part;
                   8027: 	  }
                   8028: 	}
                   8029:     }
                   8030:     foreach my $name (keys(%allnames)) {
                   8031:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8032:       my $key=":parameter_0_$name";
1.261     albertel 8033:       $$metacache{"$key.part"}='0';
                   8034:       $$metacache{"$key.name"}=$name;
1.428     albertel 8035:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8036: 					   $allnames{$name}.'_'.$name.
                   8037: 					   '.type'};
1.428     albertel 8038:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8039: 			     '.display'};
1.644     www      8040:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8041:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8042:       $$metacache{"$key.display"}=$olddis;
                   8043:     }
1.71      www      8044: }
                   8045: 
1.764     albertel 8046: # ------------------------------------------------------ Devalidate title cache
                   8047: 
                   8048: sub devalidate_title_cache {
                   8049:     my ($url)=@_;
                   8050:     if (!$env{'request.course.id'}) { return; }
                   8051:     my $symb=&symbread($url);
                   8052:     if (!$symb) { return; }
                   8053:     my $key=$env{'request.course.id'}."\0".$symb;
                   8054:     &devalidate_cache_new('title',$key);
                   8055: }
                   8056: 
1.1014    droeschl 8057: # ------------------------------------------------- Get the title of a course
                   8058: 
                   8059: sub current_course_title {
                   8060:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8061: }
1.301     www      8062: # ------------------------------------------------- Get the title of a resource
                   8063: 
                   8064: sub gettitle {
                   8065:     my $urlsymb=shift;
                   8066:     my $symb=&symbread($urlsymb);
1.534     albertel 8067:     if ($symb) {
1.620     albertel 8068: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8069: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8070: 	if (defined($cached)) { 
                   8071: 	    return $result;
                   8072: 	}
1.534     albertel 8073: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8074: 	my $title='';
1.907     albertel 8075: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8076: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8077: 	} else {
                   8078: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8079: 		    &GDBM_READER(),0640)) {
                   8080: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8081: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8082: 		untie(%bighash);
                   8083: 	    }
1.534     albertel 8084: 	}
                   8085: 	$title=~s/\&colon\;/\:/gs;
                   8086: 	if ($title) {
1.599     albertel 8087: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8088: 	}
                   8089: 	$urlsymb=$url;
                   8090:     }
                   8091:     my $title=&metadata($urlsymb,'title');
                   8092:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8093:     return $title;
1.301     www      8094: }
1.613     albertel 8095: 
1.614     albertel 8096: sub get_slot {
                   8097:     my ($which,$cnum,$cdom)=@_;
                   8098:     if (!$cnum || !$cdom) {
1.790     albertel 8099: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8100: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8101: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8102:     }
1.703     albertel 8103:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8104:     my %slotinfo;
                   8105:     if (exists($remembered{$key})) {
                   8106: 	$slotinfo{$which} = $remembered{$key};
                   8107:     } else {
                   8108: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8109: 	&Apache::lonhomework::showhash(%slotinfo);
                   8110: 	my ($tmp)=keys(%slotinfo);
                   8111: 	if ($tmp=~/^error:/) { return (); }
                   8112: 	$remembered{$key} = $slotinfo{$which};
                   8113:     }
1.616     albertel 8114:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8115: 	return %{$slotinfo{$which}};
                   8116:     }
                   8117:     return $slotinfo{$which};
1.614     albertel 8118: }
1.31      www      8119: # ------------------------------------------------- Update symbolic store links
                   8120: 
                   8121: sub symblist {
                   8122:     my ($mapname,%newhash)=@_;
1.438     www      8123:     $mapname=&deversion(&declutter($mapname));
1.31      www      8124:     my %hash;
1.620     albertel 8125:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8126:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8127:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8128: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8129: 		next if ($url eq 'last_known'
                   8130: 			 && $env{'form.no_update_last_known'});
                   8131: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8132: 						    $newhash{$url}->[1],
                   8133: 						    $newhash{$url}->[0]);
1.191     harris41 8134:             }
1.31      www      8135:             if (untie(%hash)) {
                   8136: 		return 'ok';
                   8137:             }
                   8138:         }
                   8139:     }
                   8140:     return 'error';
1.212     www      8141: }
                   8142: 
                   8143: # --------------------------------------------------------------- Verify a symb
                   8144: 
                   8145: sub symbverify {
1.510     www      8146:     my ($symb,$thisurl)=@_;
                   8147:     my $thisfn=$thisurl;
1.439     www      8148:     $thisfn=&declutter($thisfn);
1.215     www      8149: # direct jump to resource in page or to a sequence - will construct own symbs
                   8150:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8151: # check URL part
1.409     www      8152:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8153: 
1.431     www      8154:     unless ($url eq $thisfn) { return 0; }
1.213     www      8155: 
1.216     www      8156:     $symb=&symbclean($symb);
1.510     www      8157:     $thisurl=&deversion($thisurl);
1.439     www      8158:     $thisfn=&deversion($thisfn);
1.213     www      8159: 
                   8160:     my %bighash;
                   8161:     my $okay=0;
1.431     www      8162: 
1.620     albertel 8163:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8164:                             &GDBM_READER(),0640)) {
1.510     www      8165:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8166:         unless ($ids) { 
1.510     www      8167:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8168:         }
                   8169:         if ($ids) {
                   8170: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8171: 	    foreach my $id (split(/\,/,$ids)) {
                   8172: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      8173:                if (
                   8174:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8175:    eq $symb) { 
1.620     albertel 8176: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8177: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8178: 		       $okay=1; 
                   8179: 		   }
                   8180: 	       }
1.216     www      8181: 	   }
                   8182:         }
1.213     www      8183: 	untie(%bighash);
                   8184:     }
                   8185:     return $okay;
1.31      www      8186: }
                   8187: 
1.210     www      8188: # --------------------------------------------------------------- Clean-up symb
                   8189: 
                   8190: sub symbclean {
                   8191:     my $symb=shift;
1.568     albertel 8192:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8193: # remove version from map
                   8194:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8195: 
1.210     www      8196: # remove version from URL
                   8197:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8198: 
1.507     www      8199: # remove wrapper
                   8200: 
1.510     www      8201:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8202:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8203:     return $symb;
1.409     www      8204: }
                   8205: 
                   8206: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8207: 
                   8208: sub encode_symb {
                   8209:     my ($map,$resid,$url)=@_;
                   8210:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8211: }
1.409     www      8212: 
                   8213: sub decode_symb {
1.568     albertel 8214:     my $symb=shift;
                   8215:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8216:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8217:     return (&fixversion($map),$resid,&fixversion($url));
                   8218: }
                   8219: 
                   8220: sub fixversion {
                   8221:     my $fn=shift;
1.609     banghart 8222:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8223:     my %bighash;
                   8224:     my $uri=&clutter($fn);
1.620     albertel 8225:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8226: # is this cached?
1.599     albertel 8227:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8228:     if (defined($cached)) { return $result; }
                   8229: # unfortunately not cached, or expired
1.620     albertel 8230:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8231: 	    &GDBM_READER(),0640)) {
                   8232:  	if ($bighash{'version_'.$uri}) {
                   8233:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8234:  	    unless (($version eq 'mostrecent') || 
                   8235: 		    ($version==&getversion($uri))) {
1.440     www      8236:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8237:  	    }
                   8238:  	}
                   8239:  	untie %bighash;
1.413     www      8240:     }
1.599     albertel 8241:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8242: }
                   8243: 
                   8244: sub deversion {
                   8245:     my $url=shift;
                   8246:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8247:     return $url;
1.210     www      8248: }
                   8249: 
1.31      www      8250: # ------------------------------------------------------ Return symb list entry
                   8251: 
                   8252: sub symbread {
1.249     www      8253:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8254:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8255:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8256: # no filename provided? try from environment
1.44      www      8257:     unless ($thisfn) {
1.620     albertel 8258:         if ($env{'request.symb'}) {
                   8259: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8260: 	}
1.620     albertel 8261: 	$thisfn=$env{'request.filename'};
1.44      www      8262:     }
1.569     albertel 8263:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8264: # is that filename actually a symb? Verify, clean, and return
                   8265:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8266: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8267: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8268: 	}
1.242     www      8269:     }
1.44      www      8270:     $thisfn=declutter($thisfn);
1.31      www      8271:     my %hash;
1.37      www      8272:     my %bighash;
                   8273:     my $syval='';
1.620     albertel 8274:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8275:         my $targetfn = $thisfn;
1.609     banghart 8276:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8277:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8278:         }
1.687     albertel 8279: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8280: 	    $targetfn=$1;
                   8281: 	}
1.620     albertel 8282:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8283:                       &GDBM_READER(),0640)) {
1.481     raeburn  8284: 	    $syval=$hash{$targetfn};
1.37      www      8285:             untie(%hash);
                   8286:         }
                   8287: # ---------------------------------------------------------- There was an entry
                   8288:         if ($syval) {
1.601     albertel 8289: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8290: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8291: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8292: 		    #return $env{$cache_str}='';
1.601     albertel 8293: 		#}    
                   8294: 		#$syval.=$1;
                   8295: 	    #}
1.37      www      8296:         } else {
                   8297: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8298:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8299:                             &GDBM_READER(),0640)) {
1.37      www      8300: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8301:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8302:               unless ($ids) { 
                   8303:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8304:               }
                   8305:               unless ($ids) {
                   8306: # alias?
                   8307: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8308:               }
1.37      www      8309:               if ($ids) {
                   8310: # ------------------------------------------------------------------- Has ID(s)
                   8311:                  my @possibilities=split(/\,/,$ids);
1.39      www      8312:                  if ($#possibilities==0) {
                   8313: # ----------------------------------------------- There is only one possibility
1.37      www      8314: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8315: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8316: 						    $resid,$thisfn);
1.249     www      8317:                  } elsif (!$donotrecurse) {
1.39      www      8318: # ------------------------------------------ There is more than one possibility
                   8319:                      my $realpossible=0;
1.800     albertel 8320:                      foreach my $id (@possibilities) {
                   8321: 			 my $file=$bighash{'src_'.$id};
1.39      www      8322:                          if (&allowed('bre',$file)) {
1.800     albertel 8323:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8324:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8325: 				$realpossible++;
1.626     albertel 8326:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8327: 						    $resid,$thisfn);
1.39      www      8328:                             }
                   8329: 			 }
1.191     harris41 8330:                      }
1.39      www      8331: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8332:                  } else {
                   8333:                      $syval='';
1.37      www      8334:                  }
                   8335: 	      }
                   8336:               untie(%bighash)
1.481     raeburn  8337:            }
1.31      www      8338:         }
1.62      www      8339:         if ($syval) {
1.620     albertel 8340: 	    return $env{$cache_str}=$syval;
1.62      www      8341:         }
1.31      www      8342:     }
1.949     raeburn  8343:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8344:     return $env{$cache_str}='';
1.31      www      8345: }
                   8346: 
                   8347: # ---------------------------------------------------------- Return random seed
                   8348: 
1.32      www      8349: sub numval {
                   8350:     my $txt=shift;
                   8351:     $txt=~tr/A-J/0-9/;
                   8352:     $txt=~tr/a-j/0-9/;
                   8353:     $txt=~tr/K-T/0-9/;
                   8354:     $txt=~tr/k-t/0-9/;
                   8355:     $txt=~tr/U-Z/0-5/;
                   8356:     $txt=~tr/u-z/0-5/;
                   8357:     $txt=~s/\D//g;
1.564     albertel 8358:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8359:     return int($txt);
1.368     albertel 8360: }
                   8361: 
1.484     albertel 8362: sub numval2 {
                   8363:     my $txt=shift;
                   8364:     $txt=~tr/A-J/0-9/;
                   8365:     $txt=~tr/a-j/0-9/;
                   8366:     $txt=~tr/K-T/0-9/;
                   8367:     $txt=~tr/k-t/0-9/;
                   8368:     $txt=~tr/U-Z/0-5/;
                   8369:     $txt=~tr/u-z/0-5/;
                   8370:     $txt=~s/\D//g;
                   8371:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8372:     my $total;
                   8373:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8374:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8375:     return int($total);
                   8376: }
                   8377: 
1.575     albertel 8378: sub numval3 {
                   8379:     use integer;
                   8380:     my $txt=shift;
                   8381:     $txt=~tr/A-J/0-9/;
                   8382:     $txt=~tr/a-j/0-9/;
                   8383:     $txt=~tr/K-T/0-9/;
                   8384:     $txt=~tr/k-t/0-9/;
                   8385:     $txt=~tr/U-Z/0-5/;
                   8386:     $txt=~tr/u-z/0-5/;
                   8387:     $txt=~s/\D//g;
                   8388:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8389:     my $total;
                   8390:     foreach my $val (@txts) { $total+=$val; }
                   8391:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8392:     return $total;
                   8393: }
                   8394: 
1.675     albertel 8395: sub digest {
                   8396:     my ($data)=@_;
                   8397:     my $digest=&Digest::MD5::md5($data);
                   8398:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8399:     my ($e,$f);
                   8400:     {
                   8401:         use integer;
                   8402:         $e=($a+$b);
                   8403:         $f=($c+$d);
                   8404:         if ($_64bit) {
                   8405:             $e=(($e<<32)>>32);
                   8406:             $f=(($f<<32)>>32);
                   8407:         }
                   8408:     }
                   8409:     if (wantarray) {
                   8410: 	return ($e,$f);
                   8411:     } else {
                   8412: 	my $g;
                   8413: 	{
                   8414: 	    use integer;
                   8415: 	    $g=($e+$f);
                   8416: 	    if ($_64bit) {
                   8417: 		$g=(($g<<32)>>32);
                   8418: 	    }
                   8419: 	}
                   8420: 	return $g;
                   8421:     }
                   8422: }
                   8423: 
1.368     albertel 8424: sub latest_rnd_algorithm_id {
1.675     albertel 8425:     return '64bit5';
1.366     albertel 8426: }
1.32      www      8427: 
1.503     albertel 8428: sub get_rand_alg {
                   8429:     my ($courseid)=@_;
1.790     albertel 8430:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8431:     if ($courseid) {
1.620     albertel 8432: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8433:     }
                   8434:     return &latest_rnd_algorithm_id();
                   8435: }
                   8436: 
1.562     albertel 8437: sub validCODE {
                   8438:     my ($CODE)=@_;
                   8439:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8440:     return 0;
                   8441: }
                   8442: 
1.491     albertel 8443: sub getCODE {
1.620     albertel 8444:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8445:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8446: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8447: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8448: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8449:     }
                   8450:     return undef;
                   8451: }
                   8452: 
1.31      www      8453: sub rndseed {
1.155     albertel 8454:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8455:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8456:     if (!defined($symb)) {
1.366     albertel 8457: 	unless ($symb=$wsymb) { return time; }
                   8458:     }
                   8459:     if (!$courseid) { $courseid=$wcourseid; }
                   8460:     if (!$domain) { $domain=$wdomain; }
                   8461:     if (!$username) { $username=$wusername }
1.503     albertel 8462:     my $which=&get_rand_alg();
1.803     albertel 8463: 
1.491     albertel 8464:     if (defined(&getCODE())) {
1.675     albertel 8465: 	if ($which eq '64bit5') {
                   8466: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8467: 	} elsif ($which eq '64bit4') {
1.575     albertel 8468: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8469: 	} else {
                   8470: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8471: 	}
1.675     albertel 8472:     } elsif ($which eq '64bit5') {
                   8473: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8474:     } elsif ($which eq '64bit4') {
                   8475: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8476:     } elsif ($which eq '64bit3') {
                   8477: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8478:     } elsif ($which eq '64bit2') {
                   8479: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8480:     } elsif ($which eq '64bit') {
                   8481: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8482:     }
                   8483:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8484: }
                   8485: 
                   8486: sub rndseed_32bit {
                   8487:     my ($symb,$courseid,$domain,$username)=@_;
                   8488:     {
                   8489: 	use integer;
                   8490: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8491: 	my $symbseed=numval($symb) << 22;
                   8492: 	my $namechck=unpack("%32C*",$username) << 17;
                   8493: 	my $nameseed=numval($username) << 12;
                   8494: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8495: 	my $courseseed=unpack("%32C*",$courseid);
                   8496: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8497: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8498: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8499: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8500: 	return $num;
                   8501:     }
                   8502: }
                   8503: 
                   8504: sub rndseed_64bit {
                   8505:     my ($symb,$courseid,$domain,$username)=@_;
                   8506:     {
                   8507: 	use integer;
                   8508: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8509: 	my $symbseed=numval($symb) << 10;
                   8510: 	my $namechck=unpack("%32S*",$username);
                   8511: 	
                   8512: 	my $nameseed=numval($username) << 21;
                   8513: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8514: 	my $courseseed=unpack("%32S*",$courseid);
                   8515: 	
                   8516: 	my $num1=$symbchck+$symbseed+$namechck;
                   8517: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8518: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8519: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8520: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8521: 	return "$num1,$num2";
1.155     albertel 8522:     }
1.366     albertel 8523: }
                   8524: 
1.443     albertel 8525: sub rndseed_64bit2 {
                   8526:     my ($symb,$courseid,$domain,$username)=@_;
                   8527:     {
                   8528: 	use integer;
                   8529: 	# strings need to be an even # of cahracters long, it it is odd the
                   8530:         # last characters gets thrown away
                   8531: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8532: 	my $symbseed=numval($symb) << 10;
                   8533: 	my $namechck=unpack("%32S*",$username.' ');
                   8534: 	
                   8535: 	my $nameseed=numval($username) << 21;
1.501     albertel 8536: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8537: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8538: 	
                   8539: 	my $num1=$symbchck+$symbseed+$namechck;
                   8540: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8541: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8542: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8543: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8544: 	return "$num1,$num2";
                   8545:     }
                   8546: }
                   8547: 
                   8548: sub rndseed_64bit3 {
                   8549:     my ($symb,$courseid,$domain,$username)=@_;
                   8550:     {
                   8551: 	use integer;
                   8552: 	# strings need to be an even # of cahracters long, it it is odd the
                   8553:         # last characters gets thrown away
                   8554: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8555: 	my $symbseed=numval2($symb) << 10;
                   8556: 	my $namechck=unpack("%32S*",$username.' ');
                   8557: 	
                   8558: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8559: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8560: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8561: 	
                   8562: 	my $num1=$symbchck+$symbseed+$namechck;
                   8563: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8564: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8565: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8566: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8567: 	
1.503     albertel 8568: 	return "$num1:$num2";
1.443     albertel 8569:     }
                   8570: }
                   8571: 
1.575     albertel 8572: sub rndseed_64bit4 {
                   8573:     my ($symb,$courseid,$domain,$username)=@_;
                   8574:     {
                   8575: 	use integer;
                   8576: 	# strings need to be an even # of cahracters long, it it is odd the
                   8577:         # last characters gets thrown away
                   8578: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8579: 	my $symbseed=numval3($symb) << 10;
                   8580: 	my $namechck=unpack("%32S*",$username.' ');
                   8581: 	
                   8582: 	my $nameseed=numval3($username) << 21;
                   8583: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8584: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8585: 	
                   8586: 	my $num1=$symbchck+$symbseed+$namechck;
                   8587: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8588: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8589: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8590: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8591: 	
                   8592: 	return "$num1:$num2";
                   8593:     }
                   8594: }
                   8595: 
1.675     albertel 8596: sub rndseed_64bit5 {
                   8597:     my ($symb,$courseid,$domain,$username)=@_;
                   8598:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8599:     return "$num1:$num2";
                   8600: }
                   8601: 
1.366     albertel 8602: sub rndseed_CODE_64bit {
                   8603:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8604:     {
1.366     albertel 8605: 	use integer;
1.443     albertel 8606: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8607: 	my $symbseed=numval2($symb);
1.491     albertel 8608: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8609: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8610: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8611: 	my $num1=$symbseed+$CODEchck;
                   8612: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8613: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8614: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8615: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8616: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8617: 	return "$num1:$num2";
1.366     albertel 8618:     }
                   8619: }
                   8620: 
1.575     albertel 8621: sub rndseed_CODE_64bit4 {
                   8622:     my ($symb,$courseid,$domain,$username)=@_;
                   8623:     {
                   8624: 	use integer;
                   8625: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8626: 	my $symbseed=numval3($symb);
                   8627: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8628: 	my $CODEseed=numval3(&getCODE());
                   8629: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8630: 	my $num1=$symbseed+$CODEchck;
                   8631: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8632: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8633: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8634: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8635: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8636: 	return "$num1:$num2";
                   8637:     }
                   8638: }
                   8639: 
1.675     albertel 8640: sub rndseed_CODE_64bit5 {
                   8641:     my ($symb,$courseid,$domain,$username)=@_;
                   8642:     my $code = &getCODE();
                   8643:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8644:     return "$num1:$num2";
                   8645: }
                   8646: 
1.366     albertel 8647: sub setup_random_from_rndseed {
                   8648:     my ($rndseed)=@_;
1.503     albertel 8649:     if ($rndseed =~/([,:])/) {
                   8650: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8651: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8652:     } else {
                   8653: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8654:     }
1.36      albertel 8655: }
                   8656: 
1.474     albertel 8657: sub latest_receipt_algorithm_id {
1.835     albertel 8658:     return 'receipt3';
1.474     albertel 8659: }
                   8660: 
1.480     www      8661: sub recunique {
                   8662:     my $fucourseid=shift;
                   8663:     my $unique;
1.835     albertel 8664:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8665: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8666: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8667:     } else {
                   8668: 	$unique=$perlvar{'lonReceipt'};
                   8669:     }
                   8670:     return unpack("%32C*",$unique);
                   8671: }
                   8672: 
                   8673: sub recprefix {
                   8674:     my $fucourseid=shift;
                   8675:     my $prefix;
1.835     albertel 8676:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8677: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8678: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8679:     } else {
                   8680: 	$prefix=$perlvar{'lonHostID'};
                   8681:     }
                   8682:     return unpack("%32C*",$prefix);
                   8683: }
                   8684: 
1.76      www      8685: sub ireceipt {
1.474     albertel 8686:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8687: 
                   8688:     my $return =&recprefix($fucourseid).'-';
                   8689: 
                   8690:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8691: 	$env{'request.state'} eq 'construct') {
                   8692: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8693: 	return $return;
                   8694:     }
                   8695: 
1.76      www      8696:     my $cuname=unpack("%32C*",$funame);
                   8697:     my $cudom=unpack("%32C*",$fudom);
                   8698:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8699:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8700:     my $cunique=&recunique($fucourseid);
1.474     albertel 8701:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8702:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8703: 
1.790     albertel 8704: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8705: 			       
                   8706: 	$return.= ($cunique%$cuname+
                   8707: 		   $cunique%$cudom+
                   8708: 		   $cusymb%$cuname+
                   8709: 		   $cusymb%$cudom+
                   8710: 		   $cucourseid%$cuname+
                   8711: 		   $cucourseid%$cudom+
                   8712: 		   $cpart%$cuname+
                   8713: 		   $cpart%$cudom);
                   8714:     } else {
                   8715: 	$return.= ($cunique%$cuname+
                   8716: 		   $cunique%$cudom+
                   8717: 		   $cusymb%$cuname+
                   8718: 		   $cusymb%$cudom+
                   8719: 		   $cucourseid%$cuname+
                   8720: 		   $cucourseid%$cudom);
                   8721:     }
                   8722:     return $return;
1.76      www      8723: }
                   8724: 
                   8725: sub receipt {
1.474     albertel 8726:     my ($part)=@_;
1.790     albertel 8727:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8728:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8729: }
1.260     ng       8730: 
1.790     albertel 8731: sub whichuser {
                   8732:     my ($passedsymb)=@_;
                   8733:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8734:     if (defined($env{'form.grade_symb'})) {
                   8735: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8736: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8737: 	if (!$allowed &&
                   8738: 	    exists($env{'request.course.sec'}) &&
                   8739: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8740: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8741: 			      '/'.$env{'request.course.sec'});
                   8742: 	}
                   8743: 	if ($allowed) {
                   8744: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8745: 	    $courseid=$tmp_courseid;
                   8746: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8747: 	    ($name)=&get_env_multiple('form.grade_username');
                   8748: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8749: 	}
                   8750:     }
                   8751:     if (!$passedsymb) {
                   8752: 	$symb=&symbread();
                   8753:     } else {
                   8754: 	$symb=$passedsymb;
                   8755:     }
                   8756:     $courseid=$env{'request.course.id'};
                   8757:     $domain=$env{'user.domain'};
                   8758:     $name=$env{'user.name'};
                   8759:     if ($name eq 'public' && $domain eq 'public') {
                   8760: 	if (!defined($env{'form.username'})) {
                   8761: 	    $env{'form.username'}.=time.rand(10000000);
                   8762: 	}
                   8763: 	$name.=$env{'form.username'};
                   8764:     }
                   8765:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8766: 
                   8767: }
                   8768: 
1.36      albertel 8769: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8770: # returns either the contents of the file or 
                   8771: # -1 if the file doesn't exist
1.481     raeburn  8772: #
                   8773: # if the target is a file that was uploaded via DOCS, 
                   8774: # a check will be made to see if a current copy exists on the local server,
                   8775: # if it does this will be served, otherwise a copy will be retrieved from
                   8776: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8777: # the local server.   
1.472     albertel 8778: 
1.36      albertel 8779: sub getfile {
1.538     albertel 8780:     my ($file) = @_;
1.609     banghart 8781:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8782:     &repcopy($file);
                   8783:     return &readfile($file);
                   8784: }
                   8785: 
                   8786: sub repcopy_userfile {
                   8787:     my ($file)=@_;
1.609     banghart 8788:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8789:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8790:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8791: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8792:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8793:     if (-e "$file") {
1.828     www      8794: # we already have a local copy, check it out
1.538     albertel 8795: 	my @fileinfo = stat($file);
1.828     www      8796: 	my $rtncode;
                   8797: 	my $info;
1.538     albertel 8798: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8799: 	if ($lwpresp ne 'ok') {
1.828     www      8800: # there is no such file anymore, even though we had a local copy
1.482     albertel 8801: 	    if ($rtncode eq '404') {
1.538     albertel 8802: 		unlink($file);
1.482     albertel 8803: 	    }
                   8804: 	    return -1;
                   8805: 	}
                   8806: 	if ($info < $fileinfo[9]) {
1.828     www      8807: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8808: 	    return 'ok';
1.828     www      8809: 	} else {
                   8810: # the file is outdated, get rid of it
                   8811: 	    unlink($file);
1.482     albertel 8812: 	}
1.828     www      8813:     }
                   8814: # one way or the other, at this point, we don't have the file
                   8815: # construct the correct path for the file
                   8816:     my @parts = ($cdom,$cnum); 
                   8817:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8818: 	push @parts, split(/\//,$1);
                   8819:     }
                   8820:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8821:     foreach my $part (@parts) {
                   8822: 	$path .= '/'.$part;
                   8823: 	if (!-e $path) {
                   8824: 	    mkdir($path,0770);
1.482     albertel 8825: 	}
                   8826:     }
1.828     www      8827: # now the path exists for sure
                   8828: # get a user agent
                   8829:     my $ua=new LWP::UserAgent;
                   8830:     my $transferfile=$file.'.in.transfer';
                   8831: # FIXME: this should flock
                   8832:     if (-e $transferfile) { return 'ok'; }
                   8833:     my $request;
                   8834:     $uri=~s/^\///;
1.980     raeburn  8835:     my $homeserver = &homeserver($cnum,$cdom);
                   8836:     my $protocol = $protocol{$homeserver};
                   8837:     $protocol = 'http' if ($protocol ne 'https');
                   8838:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8839:     my $response=$ua->request($request,$transferfile);
                   8840: # did it work?
                   8841:     if ($response->is_error()) {
                   8842: 	unlink($transferfile);
                   8843: 	&logthis("Userfile repcopy failed for $uri");
                   8844: 	return -1;
                   8845:     }
                   8846: # worked, rename the transfer file
                   8847:     rename($transferfile,$file);
1.607     raeburn  8848:     return 'ok';
1.481     raeburn  8849: }
                   8850: 
1.517     albertel 8851: sub tokenwrapper {
                   8852:     my $uri=shift;
1.980     raeburn  8853:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8854:     $uri=~s|^/||;
1.620     albertel 8855:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8856:     my $token=$1;
1.552     albertel 8857:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8858:     if ($udom && $uname && $file) {
                   8859: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8860:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  8861:         my $homeserver = &homeserver($uname,$udom);
                   8862:         my $protocol = $protocol{$homeserver};
                   8863:         $protocol = 'http' if ($protocol ne 'https');
                   8864:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8865:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8866:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8867:     } else {
                   8868:         return '/adm/notfound.html';
                   8869:     }
                   8870: }
                   8871: 
1.828     www      8872: # call with reqtype HEAD: get last modification time
                   8873: # call with reqtype GET: get the file contents
                   8874: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8875: #
1.481     raeburn  8876: sub getuploaded {
                   8877:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8878:     $uri=~s/^\///;
1.980     raeburn  8879:     my $homeserver = &homeserver($cnum,$cdom);
                   8880:     my $protocol = $protocol{$homeserver};
                   8881:     $protocol = 'http' if ($protocol ne 'https');
                   8882:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8883:     my $ua=new LWP::UserAgent;
                   8884:     my $request=new HTTP::Request($reqtype,$uri);
                   8885:     my $response=$ua->request($request);
                   8886:     $$rtncode = $response->code;
1.482     albertel 8887:     if (! $response->is_success()) {
                   8888: 	return 'failed';
                   8889:     }      
                   8890:     if ($reqtype eq 'HEAD') {
1.486     www      8891: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8892:     } elsif ($reqtype eq 'GET') {
                   8893: 	$$info = $response->content;
1.472     albertel 8894:     }
1.482     albertel 8895:     return 'ok';
1.36      albertel 8896: }
                   8897: 
1.481     raeburn  8898: sub readfile {
                   8899:     my $file = shift;
                   8900:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8901:     my $fh;
                   8902:     open($fh,"<$file");
                   8903:     my $a='';
1.800     albertel 8904:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8905:     return $a;
                   8906: }
                   8907: 
1.36      albertel 8908: sub filelocation {
1.590     banghart 8909:     my ($dir,$file) = @_;
                   8910:     my $location;
                   8911:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8912: 
                   8913:     if ($file =~ m-^/adm/-) {
                   8914: 	$file=~s-^/adm/wrapper/-/-;
                   8915: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8916:     }
1.882     albertel 8917: 
1.590     banghart 8918:     if ($file=~m:^/~:) { # is a contruction space reference
                   8919:         $location = $file;
                   8920:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8921:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8922: 	# is a correct contruction space reference
                   8923:         $location = $file;
1.956     raeburn  8924:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8925:         $location = $file;
1.609     banghart 8926:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8927:         my ($udom,$uname,$filename)=
1.811     albertel 8928:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8929:         my $home=&homeserver($uname,$udom);
                   8930:         my $is_me=0;
                   8931:         my @ids=&current_machine_ids();
                   8932:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8933:         if ($is_me) {
1.955     raeburn  8934:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8935:         } else {
                   8936:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8937:   	      $udom.'/'.$uname.'/'.$filename;
                   8938:         }
1.882     albertel 8939:     } elsif ($file =~ m-^/adm/-) {
                   8940: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8941:     } else {
                   8942:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8943:         $file=~s:^/res/:/:;
                   8944:         if ( !( $file =~ m:^/:) ) {
                   8945:             $location = $dir. '/'.$file;
                   8946:         } else {
                   8947:             $location = '/home/httpd/html/res'.$file;
                   8948:         }
1.59      albertel 8949:     }
1.590     banghart 8950:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8951:     while ($location=~m{/\.\./}) {
                   8952: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8953: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8954: 	} else {
                   8955: 	    $location=~ s{/\.\./}{/}g;
                   8956: 	}
                   8957:     } #remove dir/..
1.590     banghart 8958:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8959:     return $location;
1.46      www      8960: }
1.36      albertel 8961: 
1.46      www      8962: sub hreflocation {
                   8963:     my ($dir,$file)=@_;
1.980     raeburn  8964:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8965: 	$file=filelocation($dir,$file);
1.700     albertel 8966:     } elsif ($file=~m-^/adm/-) {
                   8967: 	$file=~s-^/adm/wrapper/-/-;
                   8968: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8969:     }
                   8970:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8971: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8972:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8973: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8974:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8975: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8976: 	    -/uploaded/$1/$2/-x;
1.46      www      8977:     }
1.913     albertel 8978:     if ($file=~ m{^/userfiles/}) {
                   8979: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8980:     }
1.462     albertel 8981:     return $file;
1.465     albertel 8982: }
                   8983: 
                   8984: sub current_machine_domains {
1.853     albertel 8985:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8986: }
                   8987: 
                   8988: sub machine_domains {
                   8989:     my ($hostname) = @_;
1.465     albertel 8990:     my @domains;
1.838     albertel 8991:     my %hostname = &all_hostnames();
1.465     albertel 8992:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8993: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8994: 	if ($hostname eq $name) {
1.844     albertel 8995: 	    push(@domains,&host_domain($id));
1.465     albertel 8996: 	}
                   8997:     }
                   8998:     return @domains;
                   8999: }
                   9000: 
                   9001: sub current_machine_ids {
1.853     albertel 9002:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9003: }
                   9004: 
                   9005: sub machine_ids {
                   9006:     my ($hostname) = @_;
                   9007:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9008:     my @ids;
1.888     albertel 9009:     my %name_to_host = &all_names();
1.889     albertel 9010:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9011: 	return @{ $name_to_host{$hostname} };
                   9012:     }
                   9013:     return;
1.31      www      9014: }
                   9015: 
1.824     raeburn  9016: sub additional_machine_domains {
                   9017:     my @domains;
                   9018:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9019:     while( my $line = <$fh>) {
                   9020:         $line =~ s/\s//g;
                   9021:         push(@domains,$line);
                   9022:     }
                   9023:     return @domains;
                   9024: }
                   9025: 
                   9026: sub default_login_domain {
                   9027:     my $domain = $perlvar{'lonDefDomain'};
                   9028:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9029:     foreach my $posdom (&current_machine_domains(),
                   9030:                         &additional_machine_domains()) {
                   9031:         if (lc($posdom) eq lc($testdomain)) {
                   9032:             $domain=$posdom;
                   9033:             last;
                   9034:         }
                   9035:     }
                   9036:     return $domain;
                   9037: }
                   9038: 
1.31      www      9039: # ------------------------------------------------------------- Declutters URLs
                   9040: 
                   9041: sub declutter {
                   9042:     my $thisfn=shift;
1.569     albertel 9043:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9044:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9045:     $thisfn=~s/^\///;
1.697     albertel 9046:     $thisfn=~s|^adm/wrapper/||;
                   9047:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9048:     $thisfn=~s/^res\///;
1.235     www      9049:     $thisfn=~s/\?.+$//;
1.268     www      9050:     return $thisfn;
                   9051: }
                   9052: 
                   9053: # ------------------------------------------------------------- Clutter up URLs
                   9054: 
                   9055: sub clutter {
                   9056:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9057:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9058: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9059:        $thisfn='/res'.$thisfn; 
                   9060:     }
1.694     albertel 9061:     if ($thisfn !~m|/adm|) {
1.695     albertel 9062: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 9063: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9064: 	} else {
                   9065: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9066: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9067: 	    if ($embstyle eq 'ssi'
                   9068: 		|| ($embstyle eq 'hdn')
                   9069: 		|| ($embstyle eq 'rat')
                   9070: 		|| ($embstyle eq 'prv')
                   9071: 		|| ($embstyle eq 'ign')) {
                   9072: 		#do nothing with these
                   9073: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9074: 		|| ($embstyle eq 'emb')
                   9075: 		|| ($embstyle eq 'wrp')) {
                   9076: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9077: 	    } elsif ($embstyle eq 'unk'
                   9078: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9079: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9080: 	    } else {
1.718     www      9081: #		&logthis("Got a blank emb style");
1.695     albertel 9082: 	    }
1.694     albertel 9083: 	}
                   9084:     }
1.31      www      9085:     return $thisfn;
1.12      www      9086: }
                   9087: 
1.787     albertel 9088: sub clutter_with_no_wrapper {
                   9089:     my $uri = &clutter(shift);
                   9090:     if ($uri =~ m-^/adm/-) {
                   9091: 	$uri =~ s-^/adm/wrapper/-/-;
                   9092: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9093:     }
                   9094:     return $uri;
                   9095: }
                   9096: 
1.557     albertel 9097: sub freeze_escape {
                   9098:     my ($value)=@_;
                   9099:     if (ref($value)) {
                   9100: 	$value=&nfreeze($value);
                   9101: 	return '__FROZEN__'.&escape($value);
                   9102:     }
                   9103:     return &escape($value);
                   9104: }
                   9105: 
1.11      www      9106: 
1.557     albertel 9107: sub thaw_unescape {
                   9108:     my ($value)=@_;
                   9109:     if ($value =~ /^__FROZEN__/) {
                   9110: 	substr($value,0,10,undef);
                   9111: 	$value=&unescape($value);
                   9112: 	return &thaw($value);
                   9113:     }
                   9114:     return &unescape($value);
                   9115: }
                   9116: 
1.436     albertel 9117: sub correct_line_ends {
                   9118:     my ($result)=@_;
                   9119:     $$result =~s/\r\n/\n/mg;
                   9120:     $$result =~s/\r/\n/mg;
1.415     albertel 9121: }
1.1       albertel 9122: # ================================================================ Main Program
                   9123: 
1.184     www      9124: sub goodbye {
1.204     albertel 9125:    &logthis("Starting Shut down");
1.443     albertel 9126: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9127:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9128: #converted
1.599     albertel 9129: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9130:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9131: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9132: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9133: #1.1 only
1.870     albertel 9134: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9135: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9136: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9137: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9138:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9139:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9140:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9141:    &flushcourselogs();
                   9142:    &logthis("Shutting down");
                   9143: }
                   9144: 
1.852     albertel 9145: sub get_dns {
1.869     albertel 9146:     my ($url,$func,$ignore_cache) = @_;
                   9147:     if (!$ignore_cache) {
                   9148: 	my ($content,$cached)=
                   9149: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9150: 	if ($cached) {
                   9151: 	    &$func($content);
                   9152: 	    return;
                   9153: 	}
                   9154:     }
                   9155: 
                   9156:     my %alldns;
1.852     albertel 9157:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9158:     foreach my $dns (<$config>) {
                   9159: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9160:         my $line = $1;
                   9161:         my ($host,$protocol) = split(/:/,$line);
                   9162:         if ($protocol ne 'https') {
                   9163:             $protocol = 'http';
                   9164:         }
                   9165: 	$alldns{$host} = $protocol;
1.869     albertel 9166:     }
                   9167:     while (%alldns) {
                   9168: 	my ($dns) = keys(%alldns);
1.852     albertel 9169: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9170: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9171: 	my $response=$ua->request($request);
1.979     raeburn  9172:         delete($alldns{$dns});
1.852     albertel 9173: 	next if ($response->is_error());
                   9174: 	my @content = split("\n",$response->content);
1.869     albertel 9175: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9176: 	&$func(\@content);
1.869     albertel 9177: 	return;
1.852     albertel 9178:     }
                   9179:     close($config);
1.871     albertel 9180:     my $which = (split('/',$url))[3];
                   9181:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9182:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9183:     my @content = <$config>;
                   9184:     &$func(\@content);
                   9185:     return;
1.852     albertel 9186: }
1.327     albertel 9187: # ------------------------------------------------------------ Read domain file
                   9188: {
1.852     albertel 9189:     my $loaded;
1.846     albertel 9190:     my %domain;
                   9191: 
1.852     albertel 9192:     sub parse_domain_tab {
                   9193: 	my ($lines) = @_;
                   9194: 	foreach my $line (@$lines) {
                   9195: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9196: 
1.846     albertel 9197: 	    chomp($line);
1.852     albertel 9198: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9199: 	    my %this_domain;
                   9200: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9201: 			       'lang_def', 'city', 'longi', 'lati',
                   9202: 			       'primary') {
                   9203: 		$this_domain{$field} = shift(@elements);
                   9204: 	    }
                   9205: 	    $domain{$name} = \%this_domain;
1.852     albertel 9206: 	}
                   9207:     }
1.864     albertel 9208: 
                   9209:     sub reset_domain_info {
                   9210: 	undef($loaded);
                   9211: 	undef(%domain);
                   9212:     }
                   9213: 
1.852     albertel 9214:     sub load_domain_tab {
1.869     albertel 9215: 	my ($ignore_cache) = @_;
                   9216: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9217: 	my $fh;
                   9218: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9219: 	    my @lines = <$fh>;
                   9220: 	    &parse_domain_tab(\@lines);
1.448     albertel 9221: 	}
1.852     albertel 9222: 	close($fh);
                   9223: 	$loaded = 1;
1.327     albertel 9224:     }
1.846     albertel 9225: 
                   9226:     sub domain {
1.852     albertel 9227: 	&load_domain_tab() if (!$loaded);
                   9228: 
1.846     albertel 9229: 	my ($name,$what) = @_;
                   9230: 	return if ( !exists($domain{$name}) );
                   9231: 
                   9232: 	if (!$what) {
                   9233: 	    return $domain{$name}{'description'};
                   9234: 	}
                   9235: 	return $domain{$name}{$what};
                   9236:     }
1.974     raeburn  9237: 
                   9238:     sub domain_info {
                   9239:         &load_domain_tab() if (!$loaded);
                   9240:         return %domain;
                   9241:     }
                   9242: 
1.327     albertel 9243: }
                   9244: 
                   9245: 
1.1       albertel 9246: # ------------------------------------------------------------- Read hosts file
                   9247: {
1.838     albertel 9248:     my %hostname;
1.844     albertel 9249:     my %hostdom;
1.845     albertel 9250:     my %libserv;
1.852     albertel 9251:     my $loaded;
1.888     albertel 9252:     my %name_to_host;
1.852     albertel 9253: 
                   9254:     sub parse_hosts_tab {
                   9255: 	my ($file) = @_;
                   9256: 	foreach my $configline (@$file) {
                   9257: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9258: 	    next if ($configline =~ /^\^/);
                   9259: 	    chomp($configline);
1.968     raeburn  9260: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9261: 	    $name=~s/\s//g;
                   9262: 	    if ($id && $domain && $role && $name) {
                   9263: 		$hostname{$id}=$name;
1.888     albertel 9264: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9265: 		$hostdom{$id}=$domain;
                   9266: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9267:                 if (defined($protocol)) {
                   9268:                     if ($protocol eq 'https') {
                   9269:                         $protocol{$id} = $protocol;
                   9270:                     } else {
                   9271:                         $protocol{$id} = 'http'; 
                   9272:                     }
1.968     raeburn  9273:                 } else {
1.969     raeburn  9274:                     $protocol{$id} = 'http';
1.968     raeburn  9275:                 }
1.852     albertel 9276: 	    }
                   9277: 	}
                   9278:     }
1.864     albertel 9279:     
                   9280:     sub reset_hosts_info {
1.897     albertel 9281: 	&purge_remembered();
1.864     albertel 9282: 	&reset_domain_info();
                   9283: 	&reset_hosts_ip_info();
1.892     albertel 9284: 	undef(%name_to_host);
1.864     albertel 9285: 	undef(%hostname);
                   9286: 	undef(%hostdom);
                   9287: 	undef(%libserv);
                   9288: 	undef($loaded);
                   9289:     }
1.1       albertel 9290: 
1.852     albertel 9291:     sub load_hosts_tab {
1.869     albertel 9292: 	my ($ignore_cache) = @_;
                   9293: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9294: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9295: 	my @config = <$config>;
                   9296: 	&parse_hosts_tab(\@config);
                   9297: 	close($config);
                   9298: 	$loaded=1;
1.1       albertel 9299:     }
1.852     albertel 9300: 
1.838     albertel 9301:     sub hostname {
1.852     albertel 9302: 	&load_hosts_tab() if (!$loaded);
                   9303: 
1.838     albertel 9304: 	my ($lonid) = @_;
                   9305: 	return $hostname{$lonid};
                   9306:     }
1.845     albertel 9307: 
1.838     albertel 9308:     sub all_hostnames {
1.852     albertel 9309: 	&load_hosts_tab() if (!$loaded);
                   9310: 
1.838     albertel 9311: 	return %hostname;
                   9312:     }
1.845     albertel 9313: 
1.888     albertel 9314:     sub all_names {
                   9315: 	&load_hosts_tab() if (!$loaded);
                   9316: 
                   9317: 	return %name_to_host;
                   9318:     }
                   9319: 
1.974     raeburn  9320:     sub all_host_domain {
                   9321:         &load_hosts_tab() if (!$loaded);
                   9322:         return %hostdom;
                   9323:     }
                   9324: 
1.845     albertel 9325:     sub is_library {
1.852     albertel 9326: 	&load_hosts_tab() if (!$loaded);
                   9327: 
1.845     albertel 9328: 	return exists($libserv{$_[0]});
                   9329:     }
                   9330: 
                   9331:     sub all_library {
1.852     albertel 9332: 	&load_hosts_tab() if (!$loaded);
                   9333: 
1.845     albertel 9334: 	return %libserv;
                   9335:     }
                   9336: 
1.841     albertel 9337:     sub get_servers {
1.852     albertel 9338: 	&load_hosts_tab() if (!$loaded);
                   9339: 
1.841     albertel 9340: 	my ($domain,$type) = @_;
                   9341: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9342: 	                                          : %hostname;
                   9343: 	my %result;
1.842     albertel 9344: 	if (ref($domain) eq 'ARRAY') {
                   9345: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9346: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9347: 		    $result{$host} = $hostname;
                   9348: 		}
                   9349: 	    }
                   9350: 	} else {
                   9351: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9352: 		if ($hostdom{$host} eq $domain) {
                   9353: 		    $result{$host} = $hostname;
                   9354: 		}
1.841     albertel 9355: 	    }
                   9356: 	}
                   9357: 	return %result;
                   9358:     }
1.845     albertel 9359: 
1.844     albertel 9360:     sub host_domain {
1.852     albertel 9361: 	&load_hosts_tab() if (!$loaded);
                   9362: 
1.844     albertel 9363: 	my ($lonid) = @_;
                   9364: 	return $hostdom{$lonid};
                   9365:     }
                   9366: 
1.841     albertel 9367:     sub all_domains {
1.852     albertel 9368: 	&load_hosts_tab() if (!$loaded);
                   9369: 
1.841     albertel 9370: 	my %seen;
                   9371: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9372: 	return @uniq;
                   9373:     }
1.1       albertel 9374: }
                   9375: 
1.847     albertel 9376: { 
                   9377:     my %iphost;
1.856     albertel 9378:     my %name_to_ip;
                   9379:     my %lonid_to_ip;
1.869     albertel 9380: 
1.847     albertel 9381:     sub get_hosts_from_ip {
                   9382: 	my ($ip) = @_;
                   9383: 	my %iphosts = &get_iphost();
                   9384: 	if (ref($iphosts{$ip})) {
                   9385: 	    return @{$iphosts{$ip}};
                   9386: 	}
                   9387: 	return;
1.839     albertel 9388:     }
1.864     albertel 9389:     
                   9390:     sub reset_hosts_ip_info {
                   9391: 	undef(%iphost);
                   9392: 	undef(%name_to_ip);
                   9393: 	undef(%lonid_to_ip);
                   9394:     }
1.856     albertel 9395: 
                   9396:     sub get_host_ip {
                   9397: 	my ($lonid) = @_;
                   9398: 	if (exists($lonid_to_ip{$lonid})) {
                   9399: 	    return $lonid_to_ip{$lonid};
                   9400: 	}
                   9401: 	my $name=&hostname($lonid);
                   9402:    	my $ip = gethostbyname($name);
                   9403: 	return if (!$ip || length($ip) ne 4);
                   9404: 	$ip=inet_ntoa($ip);
                   9405: 	$name_to_ip{$name}   = $ip;
                   9406: 	$lonid_to_ip{$lonid} = $ip;
                   9407: 	return $ip;
                   9408:     }
1.847     albertel 9409:     
                   9410:     sub get_iphost {
1.869     albertel 9411: 	my ($ignore_cache) = @_;
1.894     albertel 9412: 
1.869     albertel 9413: 	if (!$ignore_cache) {
                   9414: 	    if (%iphost) {
                   9415: 		return %iphost;
                   9416: 	    }
                   9417: 	    my ($ip_info,$cached)=
                   9418: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9419: 	    if ($cached) {
                   9420: 		%iphost      = %{$ip_info->[0]};
                   9421: 		%name_to_ip  = %{$ip_info->[1]};
                   9422: 		%lonid_to_ip = %{$ip_info->[2]};
                   9423: 		return %iphost;
                   9424: 	    }
                   9425: 	}
1.894     albertel 9426: 
                   9427: 	# get yesterday's info for fallback
                   9428: 	my %old_name_to_ip;
                   9429: 	my ($ip_info,$cached)=
                   9430: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9431: 	if ($cached) {
                   9432: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9433: 	}
                   9434: 
1.888     albertel 9435: 	my %name_to_host = &all_names();
                   9436: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9437: 	    my $ip;
                   9438: 	    if (!exists($name_to_ip{$name})) {
                   9439: 		$ip = gethostbyname($name);
                   9440: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9441: 		    if (defined($old_name_to_ip{$name})) {
                   9442: 			$ip = $old_name_to_ip{$name};
                   9443: 			&logthis("Can't find $name defaulting to old $ip");
                   9444: 		    } else {
                   9445: 			&logthis("Name $name no IP found");
                   9446: 			next;
                   9447: 		    }
                   9448: 		} else {
                   9449: 		    $ip=inet_ntoa($ip);
1.847     albertel 9450: 		}
                   9451: 		$name_to_ip{$name} = $ip;
                   9452: 	    } else {
                   9453: 		$ip = $name_to_ip{$name};
1.653     albertel 9454: 	    }
1.888     albertel 9455: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9456: 		$lonid_to_ip{$id} = $ip;
                   9457: 	    }
                   9458: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9459: 	}
1.869     albertel 9460: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9461: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9462: 				      48*60*60);
1.869     albertel 9463: 
1.847     albertel 9464: 	return %iphost;
1.598     albertel 9465:     }
                   9466: 
1.992     raeburn  9467:     #
                   9468:     #  Given a DNS returns the loncapa host name for that DNS 
                   9469:     # 
                   9470:     sub host_from_dns {
                   9471:         my ($dns) = @_;
                   9472:         my @hosts;
                   9473:         my $ip;
                   9474: 
1.993     raeburn  9475:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9476:             $ip = $name_to_ip{$dns};
                   9477:         }
                   9478:         if (!$ip) {
                   9479:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9480:             if (length($ip) == 4) { 
                   9481: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9482:             }
                   9483:         }
                   9484:         if ($ip) {
                   9485: 	    @hosts = get_hosts_from_ip($ip);
                   9486: 	    return $hosts[0];
                   9487:         }
                   9488:         return undef;
1.986     foxr     9489:     }
1.992     raeburn  9490: 
1.986     foxr     9491: }
                   9492: 
1.862     albertel 9493: BEGIN {
                   9494: 
                   9495: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9496:     unless ($readit) {
                   9497: {
                   9498:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9499:     %perlvar = (%perlvar,%{$configvars});
                   9500: }
                   9501: 
                   9502: 
1.1       albertel 9503: # ------------------------------------------------------ Read spare server file
                   9504: {
1.448     albertel 9505:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9506: 
                   9507:     while (my $configline=<$config>) {
                   9508:        chomp($configline);
1.284     matthew  9509:        if ($configline) {
1.784     albertel 9510: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9511: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9512: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9513:        }
                   9514:     }
1.448     albertel 9515:     close($config);
1.1       albertel 9516: }
1.11      www      9517: # ------------------------------------------------------------ Read permissions
                   9518: {
1.448     albertel 9519:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9520: 
                   9521:     while (my $configline=<$config>) {
1.448     albertel 9522: 	chomp($configline);
                   9523: 	if ($configline) {
                   9524: 	    my ($role,$perm)=split(/ /,$configline);
                   9525: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9526: 	}
1.11      www      9527:     }
1.448     albertel 9528:     close($config);
1.11      www      9529: }
                   9530: 
                   9531: # -------------------------------------------- Read plain texts for permissions
                   9532: {
1.448     albertel 9533:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9534: 
                   9535:     while (my $configline=<$config>) {
1.448     albertel 9536: 	chomp($configline);
                   9537: 	if ($configline) {
1.742     raeburn  9538: 	    my ($short,@plain)=split(/:/,$configline);
                   9539:             %{$prp{$short}} = ();
                   9540: 	    if (@plain > 0) {
                   9541:                 $prp{$short}{'std'} = $plain[0];
                   9542:                 for (my $i=1; $i<@plain; $i++) {
                   9543:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9544:                 }
                   9545:             }
1.448     albertel 9546: 	}
1.135     www      9547:     }
1.448     albertel 9548:     close($config);
1.135     www      9549: }
                   9550: 
                   9551: # ---------------------------------------------------------- Read package table
                   9552: {
1.448     albertel 9553:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9554: 
                   9555:     while (my $configline=<$config>) {
1.483     albertel 9556: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9557: 	chomp($configline);
                   9558: 	my ($short,$plain)=split(/:/,$configline);
                   9559: 	my ($pack,$name)=split(/\&/,$short);
                   9560: 	if ($plain ne '') {
                   9561: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9562: 	    $packagetab{$short}=$plain; 
                   9563: 	}
1.11      www      9564:     }
1.448     albertel 9565:     close($config);
1.329     matthew  9566: }
                   9567: 
                   9568: # ------------- set up temporary directory
                   9569: {
                   9570:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9571: 
1.11      www      9572: }
                   9573: 
1.794     albertel 9574: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9575: 				'compress_threshold'=> 20_000,
                   9576:  			        });
1.185     www      9577: 
1.281     www      9578: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9579: $dumpcount=0;
1.958     www      9580: $locknum=0;
1.22      www      9581: 
1.163     harris41 9582: &logtouch();
1.672     albertel 9583: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9584: $readit=1;
1.564     albertel 9585:     {
                   9586: 	use integer;
                   9587: 	my $test=(2**32)+1;
1.568     albertel 9588: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9589: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9590:     }
1.195     www      9591: }
1.1       albertel 9592: }
1.179     www      9593: 
1.1       albertel 9594: 1;
1.191     harris41 9595: __END__
                   9596: 
1.243     albertel 9597: =pod
                   9598: 
1.191     harris41 9599: =head1 NAME
                   9600: 
1.243     albertel 9601: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9602: 
                   9603: =head1 SYNOPSIS
                   9604: 
1.243     albertel 9605: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9606: 
                   9607:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9608: 
1.243     albertel 9609: Common parameters:
                   9610: 
                   9611: =over 4
                   9612: 
                   9613: =item *
                   9614: 
                   9615: $uname : an internal username (if $cname expecting a course Id specifically)
                   9616: 
                   9617: =item *
                   9618: 
                   9619: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9620: 
                   9621: =item *
                   9622: 
                   9623: $symb : a resource instance identifier
                   9624: 
                   9625: =item *
                   9626: 
                   9627: $namespace : the name of a .db file that contains the data needed or
                   9628: being set.
                   9629: 
                   9630: =back
                   9631: 
1.394     bowersj2 9632: =head1 OVERVIEW
1.191     harris41 9633: 
1.394     bowersj2 9634: lonnet provides subroutines which interact with the
                   9635: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9636: about classes, users, and resources.
1.243     albertel 9637: 
                   9638: For many of these objects you can also use this to store data about
                   9639: them or modify them in various ways.
1.191     harris41 9640: 
1.394     bowersj2 9641: =head2 Symbs
1.191     harris41 9642: 
1.394     bowersj2 9643: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9644: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9645: map, the resource number of the resource in the map, and the URL of
                   9646: the resource itself. The latter is somewhat redundant, but might help
                   9647: if maps change.
                   9648: 
                   9649: An example is
                   9650: 
                   9651:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9652: 
                   9653: The respective map entry is
                   9654: 
                   9655:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9656:   title="Problem 2">
                   9657:  </resource>
                   9658: 
                   9659: Symbs are used by the random number generator, as well as to store and
                   9660: restore data specific to a certain instance of for example a problem.
                   9661: 
                   9662: =head2 Storing And Retrieving Data
                   9663: 
                   9664: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9665: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9666: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9667: is is the non-critical message twin of cstore. These functions are for
                   9668: handlers to store a perl hash to a user's permanent data space in an
                   9669: easy manner, and to retrieve it again on another call. It is expected
                   9670: that a handler would use this once at the beginning to retrieve data,
                   9671: and then again once at the end to send only the new data back.
                   9672: 
                   9673: The data is stored in the user's data directory on the user's
                   9674: homeserver under the ID of the course.
                   9675: 
                   9676: The hash that is returned by restore will have all of the previous
                   9677: value for all of the elements of the hash.
                   9678: 
                   9679: Example:
                   9680: 
                   9681:  #creating a hash
                   9682:  my %hash;
                   9683:  $hash{'foo'}='bar';
                   9684: 
                   9685:  #storing it
                   9686:  &Apache::lonnet::cstore(\%hash);
                   9687: 
                   9688:  #changing a value
                   9689:  $hash{'foo'}='notbar';
                   9690: 
                   9691:  #adding a new value
                   9692:  $hash{'bar'}='foo';
                   9693:  &Apache::lonnet::cstore(\%hash);
                   9694: 
                   9695:  #retrieving the hash
                   9696:  my %history=&Apache::lonnet::restore();
                   9697: 
                   9698:  #print the hash
                   9699:  foreach my $key (sort(keys(%history))) {
                   9700:    print("\%history{$key} = $history{$key}");
                   9701:  }
                   9702: 
                   9703: Will print out:
1.191     harris41 9704: 
1.394     bowersj2 9705:  %history{1:foo} = bar
                   9706:  %history{1:keys} = foo:timestamp
                   9707:  %history{1:timestamp} = 990455579
                   9708:  %history{2:bar} = foo
                   9709:  %history{2:foo} = notbar
                   9710:  %history{2:keys} = foo:bar:timestamp
                   9711:  %history{2:timestamp} = 990455580
                   9712:  %history{bar} = foo
                   9713:  %history{foo} = notbar
                   9714:  %history{timestamp} = 990455580
                   9715:  %history{version} = 2
                   9716: 
                   9717: Note that the special hash entries C<keys>, C<version> and
                   9718: C<timestamp> were added to the hash. C<version> will be equal to the
                   9719: total number of versions of the data that have been stored. The
                   9720: C<timestamp> attribute will be the UNIX time the hash was
                   9721: stored. C<keys> is available in every historical section to list which
                   9722: keys were added or changed at a specific historical revision of a
                   9723: hash.
                   9724: 
                   9725: B<Warning>: do not store the hash that restore returns directly. This
                   9726: will cause a mess since it will restore the historical keys as if the
                   9727: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9728: 
1.394     bowersj2 9729: Calling convention:
1.191     harris41 9730: 
1.394     bowersj2 9731:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9732:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9733: 
1.394     bowersj2 9734: For more detailed information, see lonnet specific documentation.
1.191     harris41 9735: 
1.394     bowersj2 9736: =head1 RETURN MESSAGES
1.191     harris41 9737: 
1.394     bowersj2 9738: =over 4
1.191     harris41 9739: 
1.394     bowersj2 9740: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9741: 
1.394     bowersj2 9742: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9743: when the connection is brought back up
1.191     harris41 9744: 
1.394     bowersj2 9745: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9746: for later delivery
1.191     harris41 9747: 
1.967     bisitz   9748: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9749: 
1.394     bowersj2 9750: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9751: that was requested
1.191     harris41 9752: 
1.243     albertel 9753: =back
1.191     harris41 9754: 
1.243     albertel 9755: =head1 PUBLIC SUBROUTINES
1.191     harris41 9756: 
1.243     albertel 9757: =head2 Session Environment Functions
1.191     harris41 9758: 
1.243     albertel 9759: =over 4
1.191     harris41 9760: 
1.394     bowersj2 9761: =item * 
                   9762: X<appenv()>
1.949     raeburn  9763: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9764: the user envirnoment file, and will be restored for each access this
1.620     albertel 9765: user makes during this session, also modifies the %env for the current
1.949     raeburn  9766: process. Optional rolesarrayref - if defined contains a reference to an array
                   9767: of roles which are exempt from the restriction on modifying user.role entries 
                   9768: in the user's environment.db and in %env.    
1.191     harris41 9769: 
                   9770: =item *
1.394     bowersj2 9771: X<delenv()>
1.987     raeburn  9772: B<delenv($delthis,$regexp)>: removes all items from the session
                   9773: environment file that begin with $delthis. If the 
                   9774: optional second arg - $regexp - is true, $delthis is treated as a 
                   9775: regular expression, otherwise \Q$delthis\E is used. 
                   9776: The values are also deleted from the current processes %env.
1.191     harris41 9777: 
1.795     albertel 9778: =item * get_env_multiple($name) 
                   9779: 
                   9780: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9781: values may be defined and end up as an array ref.
                   9782: 
                   9783: returns an array of values
                   9784: 
1.243     albertel 9785: =back
                   9786: 
                   9787: =head2 User Information
1.191     harris41 9788: 
1.243     albertel 9789: =over 4
1.191     harris41 9790: 
                   9791: =item *
1.394     bowersj2 9792: X<queryauthenticate()>
                   9793: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9794: authentication scheme
                   9795: 
                   9796: =item *
1.394     bowersj2 9797: X<authenticate()>
                   9798: B<authenticate($uname,$upass,$udom)>: try to
                   9799: authenticate user from domain's lib servers (first use the current
                   9800: one). C<$upass> should be the users password.
1.191     harris41 9801: 
                   9802: =item *
1.394     bowersj2 9803: X<homeserver()>
                   9804: B<homeserver($uname,$udom)>: find the server which has
                   9805: the user's directory and files (there must be only one), this caches
                   9806: the answer, and also caches if there is a borken connection.
1.191     harris41 9807: 
                   9808: =item *
1.394     bowersj2 9809: X<idget()>
                   9810: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9811: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9812: username, and only 1 username per ID in a specific domain) (returns
                   9813: hash: id=>name,id=>name)
1.191     harris41 9814: 
                   9815: =item *
1.394     bowersj2 9816: X<idrget()>
                   9817: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9818: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9819: 
                   9820: =item *
1.394     bowersj2 9821: X<idput()>
                   9822: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9823: 
                   9824: =item *
1.394     bowersj2 9825: X<rolesinit()>
                   9826: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9827: 
                   9828: =item *
1.551     albertel 9829: X<getsection()>
                   9830: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9831: course $cname, return section name/number or '' for "not in course"
                   9832: and '-1' for "no section"
                   9833: 
                   9834: =item *
1.394     bowersj2 9835: X<userenvironment()>
                   9836: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9837: passed in @what from the requested user's environment, returns a hash
                   9838: 
1.858     raeburn  9839: =item * 
                   9840: X<userlog_query()>
1.859     albertel 9841: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9842: activity.log file. %filters defines filters applied when parsing the
                   9843: log file. These can be start or end timestamps, or the type of action
                   9844: - log to look for Login or Logout events, check for Checkin or
                   9845: Checkout, role for role selection. The response is in the form
                   9846: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9847: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9848: 
1.243     albertel 9849: =back
                   9850: 
                   9851: =head2 User Roles
                   9852: 
                   9853: =over 4
                   9854: 
                   9855: =item *
                   9856: 
1.810     raeburn  9857: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9858:  F: full access
                   9859:  U,I,K: authentication modes (cxx only)
                   9860:  '': forbidden
                   9861:  1: user needs to choose course
                   9862:  2: browse allowed
1.766     albertel 9863:  A: passphrase authentication needed
1.243     albertel 9864: 
                   9865: =item *
                   9866: 
                   9867: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9868: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9869: and course level
                   9870: 
                   9871: =item *
                   9872: 
1.988     raeburn  9873: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   9874: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  9875: $type is Course (default) or Community.
1.988     raeburn  9876: If $forcedefault evaluates to true, text returned will be default 
                   9877: text for $type. Otherwise, if this is a course, the text returned 
                   9878: will be a custom name for the role (if defined in the course's 
                   9879: environment).  If no custom name is defined the default is returned.
                   9880:    
1.832     raeburn  9881: =item *
                   9882: 
1.935     raeburn  9883: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9884: All arguments are optional. Returns a hash of a roles, either for
                   9885: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9886: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9887: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9888: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9889: For each key, value is set to colon-separated start and end times for
                   9890: the role.  If no username and domain are specified, will default to
1.934     raeburn  9891: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9892: of role statuses (active, future or previous), roles 
                   9893: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9894: to restrict the list of roles reported. If no array ref is 
                   9895: provided for types, will default to return only active roles.
1.834     albertel 9896: 
1.243     albertel 9897: =back
                   9898: 
                   9899: =head2 User Modification
                   9900: 
                   9901: =over 4
                   9902: 
                   9903: =item *
                   9904: 
1.957     raeburn  9905: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9906: user for the level given by URL.  Optional start and end dates (leave empty
                   9907: string or zero for "no date")
1.191     harris41 9908: 
                   9909: =item *
                   9910: 
1.243     albertel 9911: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9912: change a users, password, possible return values are: ok,
                   9913: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9914: refused
1.191     harris41 9915: 
                   9916: =item *
                   9917: 
1.243     albertel 9918: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9919: 
                   9920: =item *
                   9921: 
1.963     raeburn  9922: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9923:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9924: modify user
1.191     harris41 9925: 
                   9926: =item *
                   9927: 
1.286     matthew  9928: modifystudent
                   9929: 
1.957     raeburn  9930: modify a student's enrollment and identification information.
1.286     matthew  9931: The course id is resolved based on the current users environment.  
                   9932: This means the envoking user must be a course coordinator or otherwise
                   9933: associated with a course.
                   9934: 
1.297     matthew  9935: This call is essentially a wrapper for lonnet::modifyuser and
                   9936: lonnet::modify_student_enrollment
1.286     matthew  9937: 
                   9938: Inputs: 
                   9939: 
                   9940: =over 4
                   9941: 
1.957     raeburn  9942: =item B<$udom> Student's loncapa domain
1.286     matthew  9943: 
1.957     raeburn  9944: =item B<$uname> Student's loncapa login name
1.286     matthew  9945: 
1.964     bisitz   9946: =item B<$uid> Student/Employee ID
1.286     matthew  9947: 
1.957     raeburn  9948: =item B<$umode> Student's authentication mode
1.286     matthew  9949: 
1.957     raeburn  9950: =item B<$upass> Student's password
1.286     matthew  9951: 
1.957     raeburn  9952: =item B<$first> Student's first name
1.286     matthew  9953: 
1.957     raeburn  9954: =item B<$middle> Student's middle name
1.286     matthew  9955: 
1.957     raeburn  9956: =item B<$last> Student's last name
1.286     matthew  9957: 
1.957     raeburn  9958: =item B<$gene> Student's generation
1.286     matthew  9959: 
1.957     raeburn  9960: =item B<$usec> Student's section in course
1.286     matthew  9961: 
                   9962: =item B<$end> Unix time of the roles expiration
                   9963: 
                   9964: =item B<$start> Unix time of the roles start date
                   9965: 
                   9966: =item B<$forceid> If defined, allow $uid to be changed
                   9967: 
                   9968: =item B<$desiredhome> server to use as home server for student
                   9969: 
1.957     raeburn  9970: =item B<$email> Student's permanent e-mail address
                   9971: 
                   9972: =item B<$type> Type of enrollment (auto or manual)
                   9973: 
1.963     raeburn  9974: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9975: 
                   9976: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9977: 
1.963     raeburn  9978: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9979: 
1.963     raeburn  9980: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9981: 
1.963     raeburn  9982: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9983: 
1.286     matthew  9984: =back
1.297     matthew  9985: 
                   9986: =item *
                   9987: 
                   9988: modify_student_enrollment
                   9989: 
                   9990: Change a students enrollment status in a class.  The environment variable
                   9991: 'role.request.course' must be defined for this function to proceed.
                   9992: 
                   9993: Inputs:
                   9994: 
                   9995: =over 4
                   9996: 
                   9997: =item $udom, students domain
                   9998: 
                   9999: =item $uname, students name
                   10000: 
                   10001: =item $uid, students user id
                   10002: 
                   10003: =item $first, students first name
                   10004: 
                   10005: =item $middle
                   10006: 
                   10007: =item $last
                   10008: 
                   10009: =item $gene
                   10010: 
                   10011: =item $usec
                   10012: 
                   10013: =item $end
                   10014: 
                   10015: =item $start
                   10016: 
1.957     raeburn  10017: =item $type
                   10018: 
                   10019: =item $locktype
                   10020: 
                   10021: =item $cid
                   10022: 
                   10023: =item $selfenroll
                   10024: 
                   10025: =item $context
                   10026: 
1.297     matthew  10027: =back
                   10028: 
1.191     harris41 10029: 
                   10030: =item *
                   10031: 
1.243     albertel 10032: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10033: custom role; give a custom role to a user for the level given by URL.  Specify
                   10034: name and domain of role author, and role name
1.191     harris41 10035: 
                   10036: =item *
                   10037: 
1.243     albertel 10038: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10039: 
                   10040: =item *
                   10041: 
1.243     albertel 10042: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10043: 
                   10044: =back
                   10045: 
                   10046: =head2 Course Infomation
                   10047: 
                   10048: =over 4
1.191     harris41 10049: 
                   10050: =item *
                   10051: 
1.631     albertel 10052: coursedescription($courseid) : returns a hash of information about the
                   10053: specified course id, including all environment settings for the
                   10054: course, the description of the course will be in the hash under the
                   10055: key 'description'
1.191     harris41 10056: 
                   10057: =item *
                   10058: 
1.624     albertel 10059: resdata($name,$domain,$type,@which) : request for current parameter
                   10060: setting for a specific $type, where $type is either 'course' or 'user',
                   10061: @what should be a list of parameters to ask about. This routine caches
                   10062: answers for 5 minutes.
1.243     albertel 10063: 
1.877     foxr     10064: =item *
                   10065: 
                   10066: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10067: data base, returning a hash that is keyed by the resource name and has
                   10068: values that are the resource value.  I believe that the timestamps and
                   10069: versions are also returned.
                   10070: 
                   10071: 
1.243     albertel 10072: =back
                   10073: 
                   10074: =head2 Course Modification
                   10075: 
                   10076: =over 4
1.191     harris41 10077: 
                   10078: =item *
                   10079: 
1.243     albertel 10080: writecoursepref($courseid,%prefs) : write preferences (environment
                   10081: database) for a course
1.191     harris41 10082: 
                   10083: =item *
                   10084: 
1.1011    raeburn  10085: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10086: 
                   10087: =item *
                   10088: 
                   10089: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
1.243     albertel 10090: 
                   10091: =back
                   10092: 
                   10093: =head2 Resource Subroutines
                   10094: 
                   10095: =over 4
1.191     harris41 10096: 
                   10097: =item *
                   10098: 
1.243     albertel 10099: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10100: 
                   10101: =item *
                   10102: 
1.243     albertel 10103: repcopy($filename) : subscribes to the requested file, and attempts to
                   10104: replicate from the owning library server, Might return
1.607     raeburn  10105: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10106: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10107: resource. Expects the local filesystem pathname
                   10108: (/home/httpd/html/res/....)
                   10109: 
                   10110: =back
                   10111: 
                   10112: =head2 Resource Information
                   10113: 
                   10114: =over 4
1.191     harris41 10115: 
                   10116: =item *
                   10117: 
1.243     albertel 10118: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10119: a vairety of different possible values, $varname should be a request
                   10120: string, and the other parameters can be used to specify who and what
                   10121: one is asking about.
                   10122: 
                   10123: Possible values for $varname are environment.lastname (or other item
                   10124: from the envirnment hash), user.name (or someother aspect about the
                   10125: user), resource.0.maxtries (or some other part and parameter of a
                   10126: resource)
1.204     albertel 10127: 
                   10128: =item *
                   10129: 
1.243     albertel 10130: directcondval($number) : get current value of a condition; reads from a state
                   10131: string
1.204     albertel 10132: 
                   10133: =item *
                   10134: 
1.243     albertel 10135: condval($condidx) : value of condition index based on state
1.204     albertel 10136: 
                   10137: =item *
                   10138: 
1.243     albertel 10139: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10140: resource's metadata, $what should be either a specific key, or either
                   10141: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10142: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10143: 
                   10144: this function automatically caches all requests
1.191     harris41 10145: 
                   10146: =item *
                   10147: 
1.243     albertel 10148: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10149: network of library servers; returns file handle of where SQL and regex results
                   10150: will be stored for query
1.191     harris41 10151: 
                   10152: =item *
                   10153: 
1.243     albertel 10154: symbread($filename) : return symbolic list entry (filename argument optional);
                   10155: returns the data handle
1.191     harris41 10156: 
                   10157: =item *
                   10158: 
1.243     albertel 10159: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10160: a possible symb for the URL in $thisfn, and if is an encryypted
                   10161: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10162: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10163: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10164: 
1.191     harris41 10165: 
                   10166: =item *
                   10167: 
1.243     albertel 10168: symbclean($symb) : removes versions numbers from a symb, returns the
                   10169: cleaned symb
1.191     harris41 10170: 
                   10171: =item *
                   10172: 
1.243     albertel 10173: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10174: course map, user must be in a course for it to work.
1.191     harris41 10175: 
                   10176: =item *
                   10177: 
1.243     albertel 10178: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10179: 
                   10180: =item *
                   10181: 
1.243     albertel 10182: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10183: a random seed, all arguments are optional, if they aren't sent it uses the
                   10184: environment to derive them. Note: if symb isn't sent and it can't get one
                   10185: from &symbread it will use the current time as its return value
1.191     harris41 10186: 
                   10187: =item *
                   10188: 
1.243     albertel 10189: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10190: unfakeable, receipt
1.191     harris41 10191: 
                   10192: =item *
                   10193: 
1.620     albertel 10194: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10195: 
                   10196: =item *
                   10197: 
1.243     albertel 10198: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10199: 
                   10200: =item *
                   10201: 
1.243     albertel 10202: 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 10203: 
                   10204: =item *
                   10205: 
1.243     albertel 10206: 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 10207: 
                   10208: =item *
                   10209: 
1.243     albertel 10210: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10211: 
                   10212: =item *
                   10213: 
1.243     albertel 10214: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10215: forcing spreadsheet to reevaluate the resource scores next time.
                   10216: 
                   10217: =back
                   10218: 
                   10219: =head2 Storing/Retreiving Data
                   10220: 
                   10221: =over 4
1.191     harris41 10222: 
                   10223: =item *
                   10224: 
1.243     albertel 10225: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10226: for this url; hashref needs to be given and should be a \%hashname; the
                   10227: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10228: be derived from the env
1.191     harris41 10229: 
                   10230: =item *
                   10231: 
1.243     albertel 10232: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10233: uses critical subroutine
1.191     harris41 10234: 
                   10235: =item *
                   10236: 
1.243     albertel 10237: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10238: all args are optional
1.191     harris41 10239: 
                   10240: =item *
                   10241: 
1.717     albertel 10242: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10243: dumps the complete (or key matching regexp) namespace into a hash
                   10244: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10245: normally &store()ed into
                   10246: 
                   10247: $range should be either an integer '100' (give me the first 100
                   10248:                                            matching records)
                   10249:               or be  two integers sperated by a - with no spaces
                   10250:                  '30-50' (give me the 30th through the 50th matching
                   10251:                           records)
                   10252: 
                   10253: 
                   10254: =item *
                   10255: 
                   10256: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10257: replaces a &store() version of data with a replacement set of data
                   10258: for a particular resource in a namespace passed in the $storehash hash 
                   10259: reference
                   10260: 
                   10261: =item *
                   10262: 
1.243     albertel 10263: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10264: works very similar to store/cstore, but all data is stored in a
                   10265: temporary location and can be reset using tmpreset, $storehash should
                   10266: be a hash reference, returns nothing on success
1.191     harris41 10267: 
                   10268: =item *
                   10269: 
1.243     albertel 10270: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10271: similar to restore, but all data is stored in a temporary location and
                   10272: can be reset using tmpreset. Returns a hash of values on success,
                   10273: error string otherwise.
1.191     harris41 10274: 
                   10275: =item *
                   10276: 
1.243     albertel 10277: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10278: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10279: 
                   10280: =item *
                   10281: 
1.243     albertel 10282: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10283: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10284: 
                   10285: =item *
                   10286: 
1.243     albertel 10287: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10288: namesp ($udom and $uname are optional)
1.191     harris41 10289: 
                   10290: =item *
                   10291: 
1.702     albertel 10292: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10293: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10294: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10295: 
1.702     albertel 10296: $range should be either an integer '100' (give me the first 100
                   10297:                                            matching records)
                   10298:               or be  two integers sperated by a - with no spaces
                   10299:                  '30-50' (give me the 30th through the 50th matching
                   10300:                           records)
1.449     matthew  10301: =item *
                   10302: 
                   10303: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10304: $store can be a scalar, an array reference, or if the amount to be 
                   10305: incremented is > 1, a hash reference.
                   10306: 
                   10307: ($udom and $uname are optional)
1.191     harris41 10308: 
                   10309: =item *
                   10310: 
1.243     albertel 10311: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10312: ($udom and $uname are optional)
1.191     harris41 10313: 
                   10314: =item *
                   10315: 
1.243     albertel 10316: cput($namespace,$storehash,$udom,$uname) : critical put
                   10317: ($udom and $uname are optional)
1.191     harris41 10318: 
                   10319: =item *
                   10320: 
1.748     albertel 10321: newput($namespace,$storehash,$udom,$uname) :
                   10322: 
                   10323: Attempts to store the items in the $storehash, but only if they don't
                   10324: currently exist, if this succeeds you can be certain that you have 
                   10325: successfully created a new key value pair in the $namespace db.
                   10326: 
                   10327: 
                   10328: Args:
                   10329:  $namespace: name of database to store values to
                   10330:  $storehash: hashref to store to the db
                   10331:  $udom: (optional) domain of user containing the db
                   10332:  $uname: (optional) name of user caontaining the db
                   10333: 
                   10334: Returns:
                   10335:  'ok' -> succeeded in storing all keys of $storehash
                   10336:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10337:                         least <key> already existed in the db (other
                   10338:                         requested keys may also already exist)
1.967     bisitz   10339:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10340:  'con_lost' -> unable to contact request server
                   10341:  'refused' -> action was not allowed by remote machine
                   10342: 
                   10343: 
                   10344: =item *
                   10345: 
1.243     albertel 10346: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10347: reference filled in from namesp (encrypts the return communication)
                   10348: ($udom and $uname are optional)
1.191     harris41 10349: 
                   10350: =item *
                   10351: 
1.243     albertel 10352: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10353: critical subroutine
                   10354: 
1.806     raeburn  10355: =item *
                   10356: 
1.860     raeburn  10357: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10358: array reference filled in from namespace found in domain level on either
                   10359: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10360: 
                   10361: =item *
                   10362: 
1.860     raeburn  10363: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10364: domain level either on specified domain server ($uhome) or primary domain 
                   10365: server ($udom and $uhome are optional)
1.806     raeburn  10366: 
1.943     raeburn  10367: =item * 
                   10368: 
                   10369: get_domain_defaults($target_domain) : returns hash with defaults for
                   10370: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10371: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10372: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10373: Values are retrieved from cache (if current), or from domain's configuration.db
                   10374: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10375: or lonTabs/domain.tab. 
                   10376: 
                   10377: %domdefaults = &get_auth_defaults($target_domain);
                   10378: 
1.243     albertel 10379: =back
                   10380: 
                   10381: =head2 Network Status Functions
                   10382: 
                   10383: =over 4
1.191     harris41 10384: 
                   10385: =item *
                   10386: 
                   10387: dirlist($uri) : return directory list based on URI
                   10388: 
                   10389: =item *
                   10390: 
1.243     albertel 10391: spareserver() : find server with least workload from spare.tab
                   10392: 
1.986     foxr     10393: 
                   10394: =item *
                   10395: 
                   10396: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10397: if there is no corresponding loncapa host.
                   10398: 
1.243     albertel 10399: =back
                   10400: 
1.986     foxr     10401: 
1.243     albertel 10402: =head2 Apache Request
                   10403: 
                   10404: =over 4
1.191     harris41 10405: 
                   10406: =item *
                   10407: 
1.243     albertel 10408: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10409: localhost, posts hash
                   10410: 
                   10411: =back
                   10412: 
                   10413: =head2 Data to String to Data
                   10414: 
                   10415: =over 4
1.191     harris41 10416: 
                   10417: =item *
                   10418: 
1.243     albertel 10419: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10420: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10421: 
                   10422: =item *
                   10423: 
1.243     albertel 10424: hashref2str($hashref) : convert a hashref into a string complete with
                   10425: escaping and '=' and '&' separators, supports elements that are
                   10426: arrayrefs and hashrefs
1.191     harris41 10427: 
                   10428: =item *
                   10429: 
1.243     albertel 10430: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10431: with escaping and '&' separators, supports elements that are arrayrefs
                   10432: and hashrefs
1.191     harris41 10433: 
                   10434: =item *
                   10435: 
1.243     albertel 10436: str2hash($string) : convert string to hash using unescaping and
                   10437: splitting on '=' and '&', supports elements that are arrayrefs and
                   10438: hashrefs
1.191     harris41 10439: 
                   10440: =item *
                   10441: 
1.243     albertel 10442: str2array($string) : convert string to hash using unescaping and
                   10443: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10444: 
                   10445: =back
                   10446: 
                   10447: =head2 Logging Routines
                   10448: 
                   10449: =over 4
                   10450: 
                   10451: These routines allow one to make log messages in the lonnet.log and
                   10452: lonnet.perm logfiles.
1.191     harris41 10453: 
                   10454: =item *
                   10455: 
1.243     albertel 10456: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10457: 
                   10458: =item *
                   10459: 
1.243     albertel 10460: logthis() : append message to the normal lonnet.log file, it gets
                   10461: preiodically rolled over and deleted.
1.191     harris41 10462: 
                   10463: =item *
                   10464: 
1.243     albertel 10465: logperm() : append a permanent message to lonnet.perm.log, this log
                   10466: file never gets deleted by any automated portion of the system, only
                   10467: messages of critical importance should go in here.
                   10468: 
                   10469: =back
                   10470: 
                   10471: =head2 General File Helper Routines
                   10472: 
                   10473: =over 4
1.191     harris41 10474: 
                   10475: =item *
                   10476: 
1.481     raeburn  10477: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10478: (a) files in /uploaded
                   10479:   (i) If a local copy of the file exists - 
                   10480:       compares modification date of local copy with last-modified date for 
                   10481:       definitive version stored on home server for course. If local copy is 
                   10482:       stale, requests a new version from the home server and stores it. 
                   10483:       If the original has been removed from the home server, then local copy 
                   10484:       is unlinked.
                   10485:   (ii) If local copy does not exist -
                   10486:       requests the file from the home server and stores it. 
                   10487:   
                   10488:   If $caller is 'uploadrep':  
                   10489:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10490:     for request for files originally uploaded via DOCS. 
                   10491:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10492:   
                   10493:   Otherwise:
                   10494:      This indicates a call from the content generation phase of the request.
                   10495:      -  returns the entire contents of the file or -1.
                   10496:      
                   10497: (b) files in /res
                   10498:    - returns the entire contents of a file or -1; 
                   10499:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10500: 
1.712     albertel 10501: 
                   10502: =item *
                   10503: 
                   10504: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10505:                   reference
                   10506: 
                   10507: returns either a stat() list of data about the file or an empty list
                   10508: if the file doesn't exist or couldn't find out about it (connection
                   10509: problems or user unknown)
                   10510: 
1.191     harris41 10511: =item *
                   10512: 
1.243     albertel 10513: filelocation($dir,$file) : returns file system location of a file
                   10514: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10515: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10516: and a file of ../bob will become /a/bob)
1.191     harris41 10517: 
                   10518: =item *
                   10519: 
                   10520: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10521: filelocation except for hrefs
                   10522: 
                   10523: =item *
                   10524: 
                   10525: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10526: 
1.243     albertel 10527: =back
                   10528: 
1.608     albertel 10529: =head2 Usererfile file routines (/uploaded*)
                   10530: 
                   10531: =over 4
                   10532: 
                   10533: =item *
                   10534: 
                   10535: userfileupload(): main rotine for putting a file in a user or course's
                   10536:                   filespace, arguments are,
                   10537: 
1.620     albertel 10538:  formname - required - this is the name of the element in $env where the
1.608     albertel 10539:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10540:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10541:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10542:  coursedoc - if true, store the file in the course of the active role
                   10543:              of the current user
                   10544:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10545:          if undefined, it will be placed in "unknown"
                   10546: 
                   10547:  (This routine calls clean_filename() to remove any dangerous
                   10548:  characters from the filename, and then calls finuserfileupload() to
                   10549:  complete the transaction)
                   10550: 
                   10551:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10552:  and /adm/notfound.html if unsuccessful
                   10553: 
                   10554: =item *
                   10555: 
                   10556: clean_filename(): routine for cleaing a filename up for storage in
                   10557:                  userfile space, argument is:
                   10558: 
                   10559:  filename - proposed filename
                   10560: 
                   10561: returns: the new clean filename
                   10562: 
                   10563: =item *
                   10564: 
                   10565: finishuserfileupload(): routine that creaes and sends the file to
                   10566: userspace, probably shouldn't be called directly
                   10567: 
                   10568:   docuname: username or courseid of destination for the file
                   10569:   docudom: domain of user/course of destination for the file
                   10570:   formname: same as for userfileupload()
                   10571:   fname: filename (inculding subdirectories) for the file
                   10572: 
                   10573:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10574:  and /adm/notfound.html if unsuccessful
                   10575: 
                   10576: =item *
                   10577: 
                   10578: renameuserfile(): renames an existing userfile to a new name
                   10579: 
                   10580:   Args:
                   10581:    docuname: username or courseid of destination for the file
                   10582:    docudom: domain of user/course of destination for the file
                   10583:    old: current file name (including any subdirs under userfiles)
                   10584:    new: desired file name (including any subdirs under userfiles)
                   10585: 
                   10586: =item *
                   10587: 
                   10588: mkdiruserfile(): creates a directory is a userfiles dir
                   10589: 
                   10590:   Args:
                   10591:    docuname: username or courseid of destination for the file
                   10592:    docudom: domain of user/course of destination for the file
                   10593:    dir: dir to create (including any subdirs under userfiles)
                   10594: 
                   10595: =item *
                   10596: 
                   10597: removeuserfile(): removes a file that exists in userfiles
                   10598: 
                   10599:   Args:
                   10600:    docuname: username or courseid of destination for the file
                   10601:    docudom: domain of user/course of destination for the file
                   10602:    fname: filname to delete (including any subdirs under userfiles)
                   10603: 
                   10604: =item *
                   10605: 
                   10606: removeuploadedurl(): convience function for removeuserfile()
                   10607: 
                   10608:   Args:
                   10609:    url:  a full /uploaded/... url to delete
                   10610: 
1.747     albertel 10611: =item * 
                   10612: 
                   10613: get_portfile_permissions():
                   10614:   Args:
                   10615:     domain: domain of user or course contain the portfolio files
                   10616:     user: name of user or num of course contain the portfolio files
                   10617:   Returns:
                   10618:     hashref of a dump of the proper file_permissions.db
                   10619:    
                   10620: 
                   10621: =item * 
                   10622: 
                   10623: get_access_controls():
                   10624: 
                   10625: Args:
                   10626:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10627:   group: (optional) the group you want the files associated with
                   10628:   file: (optional) the file you want access info on
                   10629: 
                   10630: Returns:
1.749     raeburn  10631:     a hash (keys are file names) of hashes containing
                   10632:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10633:         values are XML containing access control settings (see below) 
1.747     albertel 10634: 
                   10635: Internal notes:
                   10636: 
1.749     raeburn  10637:  access controls are stored in file_permissions.db as key=value pairs.
                   10638:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10639:         where scope -> public,guest,course,group,domains or users.
                   10640:               end -> UNIX time for end of access (0 -> no end date)
                   10641:               start -> UNIX time for start of access
                   10642: 
                   10643:     value -> XML description of access control
                   10644:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10645:             <start></start>
                   10646:             <end></end>
                   10647: 
                   10648:             <password></password>  for scope type = guest
                   10649: 
                   10650:             <domain></domain>     for scope type = course or group
                   10651:             <number></number>
                   10652:             <roles id="">
                   10653:              <role></role>
                   10654:              <access></access>
                   10655:              <section></section>
                   10656:              <group></group>
                   10657:             </roles>
                   10658: 
                   10659:             <dom></dom>         for scope type = domains
                   10660: 
                   10661:             <users>             for scope type = users
                   10662:              <user>
                   10663:               <uname></uname>
                   10664:               <udom></udom>
                   10665:              </user>
                   10666:             </users>
                   10667:            </scope> 
                   10668:               
                   10669:  Access data is also aggregated for each file in an additional key=value pair:
                   10670:  key -> path to file/file_name\0accesscontrol 
                   10671:  value -> reference to hash
                   10672:           hash contains key = value pairs
                   10673:           where key = uniqueID:scope_end_start
                   10674:                 value = UNIX time record was last updated
                   10675: 
                   10676:           Used to improve speed of look-ups of access controls for each file.  
                   10677:  
                   10678:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10679: 
                   10680: modify_access_controls():
                   10681: 
                   10682: Modifies access controls for a portfolio file
                   10683: Args
                   10684: 1. file name
                   10685: 2. reference to hash of required changes,
                   10686: 3. domain
                   10687: 4. username
                   10688:   where domain,username are the domain of the portfolio owner 
                   10689:   (either a user or a course) 
                   10690: 
                   10691: Returns:
                   10692: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10693: 2. result of deletions ('ok' or 'error', with error message).
                   10694: 3. reference to hash of any new or updated access controls.
                   10695: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10696:    key = integer (inbound ID)
                   10697:    value = uniqueID  
1.747     albertel 10698: 
1.608     albertel 10699: =back
                   10700: 
1.243     albertel 10701: =head2 HTTP Helper Routines
                   10702: 
                   10703: =over 4
                   10704: 
1.191     harris41 10705: =item *
                   10706: 
                   10707: escape() : unpack non-word characters into CGI-compatible hex codes
                   10708: 
                   10709: =item *
                   10710: 
                   10711: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10712: 
1.243     albertel 10713: =back
                   10714: 
                   10715: =head1 PRIVATE SUBROUTINES
                   10716: 
                   10717: =head2 Underlying communication routines (Shouldn't call)
                   10718: 
                   10719: =over 4
                   10720: 
                   10721: =item *
                   10722: 
                   10723: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10724: 
                   10725: =item *
                   10726: 
                   10727: reply() : uses subreply to send a message to remote machine, logs all failures
                   10728: 
                   10729: =item *
                   10730: 
                   10731: critical() : passes a critical message to another server; if cannot
                   10732: get through then place message in connection buffer directory and
                   10733: returns con_delayed, if incapable of saving message, returns
                   10734: con_failed
                   10735: 
                   10736: =item *
                   10737: 
                   10738: reconlonc() : tries to reconnect lonc client processes.
                   10739: 
                   10740: =back
                   10741: 
                   10742: =head2 Resource Access Logging
                   10743: 
                   10744: =over 4
                   10745: 
                   10746: =item *
                   10747: 
                   10748: flushcourselogs() : flush (save) buffer logs and access logs
                   10749: 
                   10750: =item *
                   10751: 
                   10752: courselog($what) : save message for course in hash
                   10753: 
                   10754: =item *
                   10755: 
                   10756: courseacclog($what) : save message for course using &courselog().  Perform
                   10757: special processing for specific resource types (problems, exams, quizzes, etc).
                   10758: 
1.191     harris41 10759: =item *
                   10760: 
                   10761: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10762: as a PerlChildExitHandler
1.243     albertel 10763: 
                   10764: =back
                   10765: 
                   10766: =head2 Other
                   10767: 
                   10768: =over 4
                   10769: 
                   10770: =item *
                   10771: 
                   10772: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10773: 
                   10774: =back
                   10775: 
                   10776: =cut
1.877     foxr     10777: 

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